相关疑难解决方法(0)

pandas.to_datetime时间字符串格式不一致

我试图使用.将pandas.DataFrame字符串格式的索引转换为日期时间索引pandas.to_datetime().

进口大熊猫:

In [1]: import pandas as pd

In [2]: pd.__version__
Out[2]: '0.10.1'
Run Code Online (Sandbox Code Playgroud)

创建一个示例DataFrame:

In [3]: d = {'data' : pd.Series([1.,2.], index=['26/12/2012', '10/01/2013'])}

In [4]: df=pd.DataFrame(d)
Run Code Online (Sandbox Code Playgroud)

看看指数.请注意,日期格式为日/月/年:

In [5]: df.index
Out[5]: Index([26/12/2012, 10/01/2013], dtype=object)
Run Code Online (Sandbox Code Playgroud)

将索引转换为datetime:

In [6]: pd.to_datetime(df.index)
Out[6]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-12-26 00:00:00, 2013-10-01 00:00:00]
Length: 2, Freq: None, Timezone: None
Run Code Online (Sandbox Code Playgroud)

在此阶段,您可以看到每个条目的日期格式的格式不同.第一个很好,第二个月和天交换.

这是我想写的,但避免日期字符串的格式不一致:

In [7]: df.set_index(pd.to_datetime(df.index))
Out[7]: 
data
2012-12-26   1
2013-10-01   2
Run Code Online (Sandbox Code Playgroud)

我想第一个条目是正确的,因为函数'知道'没有26个月,所以不选择默认的月/日/年格式.

还有其他/更好的方法吗?我可以将格式传递给to_datetime()函数吗?

谢谢.

编辑:

我找到了一种方法,没有pandas.to_datetime:

import datetime.datetime as dt
date_string_list = df.index.tolist() …
Run Code Online (Sandbox Code Playgroud)

python datetime pandas

5
推荐指数
1
解决办法
6960
查看次数

标签 统计

datetime ×1

pandas ×1

python ×1