Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在熊猫数据帧中将日期时间格式2020-09-16 00:00:00转换为20200916_Python_Python 3.x_Pandas_Dataframe_Datetime - Fatal编程技术网

Python 在熊猫数据帧中将日期时间格式2020-09-16 00:00:00转换为20200916

Python 在熊猫数据帧中将日期时间格式2020-09-16 00:00:00转换为20200916,python,python-3.x,pandas,dataframe,datetime,Python,Python 3.x,Pandas,Dataframe,Datetime,下面是python中的panda数据帧 full_name serial Date_YMD prc1 prc2 volume bottle_a AX80 2020-09-22 00:00:00 12874.50 12927.75 61023.0 bottle_a AX80 2020-09-23 00:00:00 12878.50 12926.75 61023.0 bottle_a AX80 2

下面是python中的panda数据帧

full_name  serial  Date_YMD                  prc1     prc2    volume
 bottle_a  AX80    2020-09-22 00:00:00   12874.50  12927.75   61023.0 
 bottle_a  AX80    2020-09-23 00:00:00   12878.50  12926.75   61023.0
 bottle_a  AX80    2020-09-24 00:00:00   12872.50  12928.75   61023.0
我想将列
date\u YMD
中的日期格式值转换为转换后的类似内容

full_name  serial  Date_YMD        prc1     prc2    volume
 bottle_a  AX80    20200922    12874.50  12927.75   61023.0 
 bottle_a  AX80    20200923    12878.50  12926.75   61023.0
 bottle_a  AX80    20200924    12872.50  12928.75   61023.0

我使用的是python 3.8,假设您的
Date\u YMD
列是datetime对象,如果不将其转换为 由pd.到datetime的时间

这样就可以完成任务,但它会将datetime对象转换为字符串

df['Date_YMD'] = (df['Date_YMD'].dt.date).apply(lambda x: x.strftime("%Y%m%d"))

您需要首先将
Date\u YMD
列转换为
datetime
列:

In [731]: df.Date_YMD = pd.to_datetime(df.Date_YMD)
然后,您可以使用如下方法格式化datetime列:

In [735]: df.Date_YMD = df.Date_YMD.dt.strftime('%Y%m%d')

In [736]: df
Out[736]: 
  full_name serial  Date_YMD     prc1      prc2   volume
0  bottle_a   AX80  20200922  12874.5  12927.75  61023.0
1  bottle_a   AX80  20200923  12878.5  12926.75  61023.0
2  bottle_a   AX80  20200924  12872.5  12928.75  61023.0

尽可能避免使用
apply
,因为它有点慢。
apply
本质上增加了另一个循环-但是,什么慢,什么不慢取决于用例。在这里,
strftime
本身很可能是瓶颈,而不是在应用的lambda函数中调用它。我反对使用apply/lambda的理由是可读性——使用dt访问器对我来说似乎更清楚。