gpt4 book ai didi

python - 在 Pandas 数据框中将日期转换为日期时间格式时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:44:29 24 4
gpt4 key购买 nike

这是数据框。我希望此处的日期采用 '%Y-%m-%d %H:%M:%S' 格式。

import pandas as pd
df2 = pd.DataFrame([['2017-18','','','','','','','','','','','',''], ['COMPANIES', '01-APR-2017', '01-MAY-2017', '01-JUN-2017',
'01-JULY-2017', '01-AUG-2017', '01-SEP-2017', '01-OCT-2017', '01-NOV-2017', '01-DEC-2017', '01-JAN-2018', '01-FEB-2018', '01-MAR-2018']])

我试过了,

df2.iloc[1, 1:] = df2.iloc[1, 1:].str.replace("JULY", "JUL")
df2.iloc[1, 1:] = df2.iloc[1, 1:].apply(pd.to_datetime, format = '%d-%b-%Y')

但是,它给出:

          0                    1                    2                    3   \
0 2017-18
1 COMPANIES 1491004800000000000 1493596800000000000 1496275200000000000

4 5 6 \
0
1 1498867200000000000 1501545600000000000 1504224000000000000

7 8 9 \
0
1 1506816000000000000 1509494400000000000 1512086400000000000

10 11 12
0
1 1514764800000000000 1517443200000000000 1519862400000000000

我错过了什么吗?有没有其他方法可以实现所需格式的日期?

我什至试过:

for i in df2.iloc[1, 1:]:
i = datetime.datetime.fromtimestamp(int(i)).strftime('%Y-%m-%d %H:%M:%S')

但给出了一个 ValueError: timestamp out of range for platform localtime()/gmtime() function

最佳答案

在我看来,您应该转置数据框并使用 dateutil.parser,它在日期输入格式方面更加灵活。

在结构上,pandas 在您具有固定类型的系列(或列)时效果最佳且最直观。

设置

import pandas as pd
from dateutil import parser

df2 = pd.DataFrame([['2017-18','','','','','','','','','','','',''], ['COMPANIES', '01-APR-2017', '01-MAY-2017', '01-JUN-2017',
'01-JULY-2017', '01-AUG-2017', '01-SEP-2017', '01-OCT-2017', '01-NOV-2017', '01-DEC-2017', '01-JAN-2018', '01-FEB-2018', '01-MAR-2018']])

解决方案

res = df2.T.iloc[1:, 1].apply(parser.parse)

结果

print(res)

1 2017-04-01
2 2017-05-01
3 2017-06-01
4 2017-07-01
5 2017-08-01
6 2017-09-01
7 2017-10-01
8 2017-11-01
9 2017-12-01
10 2018-01-01
11 2018-02-01
12 2018-03-01
Name: 1, dtype: datetime64[ns]

关于python - 在 Pandas 数据框中将日期转换为日期时间格式时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com