我有一个包含a到f列的数据框。列b,d和f是我想使用pandas.to_datetime生成datetime类型的日期。这是我的代码:
file = pd.read_csv(filename, usecols=my_columns, engine='python')
df = pd.DataFrame(file)
df['b', 'd', 'f'] = pd.to_datetime(df['b', 'd', 'f'])
print('FINISHED')
然而,当我执行我的代码时,似乎卡住了。我没有收到任何错误,但是" FINISHED"从不打印。我认为我在to_datetime行的语法不正确,但我不知道为什么,我不知道如何解决它。我的数据框中有大约1,000行。我对Python很新。我做错了什么?
由于
答案 0 :(得分:1)
我认为你错误地使用了to_datetime方法。试试吧
cols = ['b','d','f']
for col in cols:
df[col] = pd.to_datetime(col)
答案 1 :(得分:0)
示例从excel中获取保存为csv的日期。
In [18]: df
Out[18]:
a b c
0 1/1/17 1/1/17 1/1/17
1 1/2/17 1/2/17 1/2/17
2 1/3/17 1/3/17 1/3/17
7 1/8/17 1/8/17 1/8/17
8 1/9/17 1/9/17 1/9/17
9 1/10/17 1/10/17 1/10/17
使用强制来避免像弹出这样的错误。
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
运行循环。
In [26]: for col in df.columns:
...: df[col] = pd.to_datetime(df[col], errors='coerce')
你得到了你想要的输出。
In [27]: df
Out[27]:
a b c
0 NaT 2017-01-01 2017-01-01
1 2017-01-02 2017-01-02 2017-01-02
2 2017-01-03 2017-01-03 2017-01-03
3 2017-01-04 2017-01-04 2017-01-04
4 2017-01-05 2017-01-05 2017-01-05
5 2017-01-06 2017-01-06 2017-01-06
6 2017-01-07 2017-01-07 2017-01-07
7 2017-01-08 2017-01-08 2017-01-08
8 2017-01-09 2017-01-09 2017-01-09
9 2017-01-10 2017-01-10 2017-01-10