首页 > 解决方案 > to_datetime() 在 python pandas 中做了什么?

问题描述

我有一个代码df['date'] = pd.to_datetime(df['date'], format = '%Y-%m-%d') ,我不明白这段代码的作用?有人可以解释一下吗。

标签: pythonpandas

解决方案


此代码将您的列date从字符串转换为日期时间 dtype。该format参数向 pandas 指示如何解释字符串。

例子:

>>> df
       Date
0  07/10/14
1  30/03/15
2  07/12/15
3  09/12/15
4  30/01/17

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Date    5 non-null      object  # <- HERE
dtypes: object(1)
memory usage: 168.0+ bytes

转换为日期时间:

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')
>>> df
        Date
0 2014-10-07
1 2015-03-30
2 2015-12-07
3 2015-12-09
4 2017-01-30

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Date    5 non-null      datetime64[ns]  # <- HERE
dtypes: datetime64[ns](1)
memory usage: 168.0 bytes

推荐阅读