我有一个包含一些数据的 CSV 文件,如下所示:
我有很多这样的文件,我想将它们读入 DataFrame:
df = pd.read_csv(filepath, engine='c')
df['closingDate'] = pd.to_datetime(df['closingDate'], format='%dd-%mmm-%yy')
df['Fut Expiration Date'] = pd.to_datetime(df['Fut Expiration Date'], format='%d-%m-%yy')
Run Code Online (Sandbox Code Playgroud)
我尝试了多种格式,但似乎都不起作用。有替代方案吗?
其实你并不需要在此指定的格式。格式是明确的,如果我们在不指定格式的情况下对其进行转换,我们将得到:
>>> df
Date
0 1-Dec-99
1 1-Jul-99
2 1-Jun-99
3 1-Nov-99
4 1-Oct-99
5 1-Sep-99
6 2-Aug-99
7 2-Dec-99
>>> pd.to_datetime(df['Date'])
0 1999-12-01
1 1999-07-01
2 1999-06-01
3 1999-11-01
4 1999-10-01
5 1999-09-01
6 1999-08-02
7 1999-12-02
Name: Date, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
或者,我们可以在datetime
模块 [Python-doc]的文档中查找格式。我们在这里看到:
Run Code Online (Sandbox Code Playgroud)%d Day of the month as a zero-padded 01, 02, …, 31 decimal number. %b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US); Jan, Feb, …, Dez (de_DE) %y Year without century as a 00, 01, …, 99 zero-padded decimal number.
所以我们可以指定格式为:
>>> pd.to_datetime(df['Date'], format='%d-%b-%y')
0 1999-12-01
1 1999-07-01
2 1999-06-01
3 1999-11-01
4 1999-10-01
5 1999-09-01
6 1999-08-02
7 1999-12-02
Name: Date, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3875 次 |
最近记录: |