python - to_datetime() 在 python pandas 中做了什么?
问题描述
我有一个代码df['date'] = pd.to_datetime(df['date'], format = '%Y-%m-%d')
,我不明白这段代码的作用?有人可以解释一下吗。
解决方案
此代码将您的列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
推荐阅读
- javascript - 服务器不听快递
- eclipse - 通过 Eclipse 运行 SoapUI 项目时出错
- python - 用户注册时未创建 django 令牌
- ios - 在 Storyboard 中的 StackView 内调整 UIButton 的大小
- deployment - netlify 部署后“站点尚未部署”
- java - 在 groupingBy 期间为重复记录组中的字段分配唯一值
- redux-toolkit - 请求后更新其他切片
- css - 在电子中拖动物体时出现白框
- django - 使用相关字段名称查询
- python - 从 Kafka Sparkstreaming 转换 JSON 中的数据类型