数据清洗之 日期格式数据处理

本文介绍如何在Pandas中使用to_datetime()方法将文本格式的日期转换为日期格式,利用dt方法提取年月日等属性,以及处理时间差数据,将其转换为指定时间单位的数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日期格式数据处理

  • Pandas中使用to_datetime()方法将文本格式转换为日期格式
  • dataframe数据类型如果为datetime64,可以使用dt方法取出年月日等
  • 对于时间差数据,可以使用timedelta函数将其转换为指定时间单位的数值
  • 时间差数据,可以使用dt方法访问其常用属性
import pandas as pd
import numpy as np
import os
os.getcwd()
'D:\\Jupyter\\notebook\\Python数据清洗实战\\数据清洗之数据转换'
os.chdir('D:\\Jupyter\\notebook\\Python数据清洗实战\\数据')
df = pd.read_csv('baby_trade_history.csv', encoding='utf-8', dtype={'user_id':str})
df.head(5)
user_idauction_idcat_idcat1propertybuy_mountday
078629554441098319944500148665002252021458:86755362;13023209:3593274;10984217:21985...220140919
153211045717916191097500119932821458:11399317;1628862:3251296;21475:137325;16...120131011
224901372521896936223500124615001481521458:30992;1628665:92012;1628665:3233938;1628...120131011
391705600712515996043500188315001481521458:15841995;21956:3494076;27000458:59723383...220141023
444406917320487688075500136365000816821458:30992;13658074:3323064;1628665:3233941;1...120141103
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29971 entries, 0 to 29970
Data columns (total 7 columns):
user_id       29971 non-null object
auction_id    29971 non-null int64
cat_id        29971 non-null int64
cat1          29971 non-null int64
property      29827 non-null object
buy_mount     29971 non-null int64
day           29971 non-null int64
dtypes: int64(5), object(2)
memory usage: 1.6+ MB
df['buy_date'] = pd.to_datetime(df['day'], format='%Y%m%d', errors='coerce')
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29971 entries, 0 to 29970
Data columns (total 8 columns):
user_id       29971 non-null object
auction_id    29971 non-null int64
cat_id        29971 non-null int64
cat1          29971 non-null int64
property      29827 non-null object
buy_mount     29971 non-null int64
day           29971 non-null int64
buy_date      29971 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(5), object(2)
memory usage: 1.8+ MB
df.head(5)
user_idauction_idcat_idcat1propertybuy_mountdaybuy_date
078629554441098319944500148665002252021458:86755362;13023209:3593274;10984217:21985...2201409192014-09-19
153211045717916191097500119932821458:11399317;1628862:3251296;21475:137325;16...1201310112013-10-11
224901372521896936223500124615001481521458:30992;1628665:92012;1628665:3233938;1628...1201310112013-10-11
391705600712515996043500188315001481521458:15841995;21956:3494076;27000458:59723383...2201410232014-10-23
444406917320487688075500136365000816821458:30992;13658074:3323064;1628665:3233941;1...1201411032014-11-03
# 使用dt方法提取属性
# df['buy_date'].dt.year  # 提取年
# df['buy_date'].dt.month  # 提取月
# df['buy_date'].dt.day  # 提取天
df['diff_day'] = pd.datetime.now() - df['buy_date']  # 时间差格式
df.head(5)
user_idauction_idcat_idcat1propertybuy_mountdaybuy_datediff_day
078629554441098319944500148665002252021458:86755362;13023209:3593274;10984217:21985...2201409192014-09-192034 days 22:32:35.614788
153211045717916191097500119932821458:11399317;1628862:3251296;21475:137325;16...1201310112013-10-112377 days 22:32:35.614788
224901372521896936223500124615001481521458:30992;1628665:92012;1628665:3233938;1628...1201310112013-10-112377 days 22:32:35.614788
391705600712515996043500188315001481521458:15841995;21956:3494076;27000458:59723383...2201410232014-10-232000 days 22:32:35.614788
444406917320487688075500136365000816821458:30992;13658074:3323064;1628665:3233941;1...1201411032014-11-031989 days 22:32:35.614788
df.dtypes
user_id                object
auction_id              int64
cat_id                  int64
cat1                    int64
property               object
buy_mount               int64
day                     int64
buy_date       datetime64[ns]
diff_day      timedelta64[ns]
dtype: object
# 使用dt方法提取属性
# df['diff_day'].dt.days  # 提取天数
# df['diff_day'].dt.seconds  # 提取秒
# df['diff_day'].dt.microseconds  # 提取纳秒
# 将时间差转换为规定的格式
df['时间差'] = df['diff_day']/pd.Timedelta('1 D')  # 转换为天数
df['时间差'].head(5)
0    2034.939301
1    2377.939301
2    2377.939301
3    2000.939301
4    1989.939301
Name: 时间差, dtype: float64
df['时间差'] = df['diff_day']/pd.Timedelta('1 H')  # 转换为小时
df['时间差'].head(5)
0    48838.543226
1    57070.543226
2    57070.543226
3    48022.543226
4    47758.543226
Name: 时间差, dtype: float64
df['时间差'] = df['diff_day']/pd.Timedelta('1 M')  # 转换为分钟数
df['时间差'].head(5)
0    2.930313e+06
1    3.424233e+06
2    3.424233e+06
3    2.881353e+06
4    2.865513e+06
Name: 时间差, dtype: float64
# 将科学计数转换为小数
df['时间差'].head(5).round(decimals=3)
0    2930312.594
1    3424232.594
2    3424232.594
3    2881352.594
4    2865512.594
Name: 时间差, dtype: float64
# D: 天  M: 月  Y: 年
# 转换为天数
df['diff_day'].astype('timedelta64[D]').head(5)
0    2034.0
1    2377.0
2    2377.0
3    2000.0
4    1989.0
Name: diff_day, dtype: float64
# 转换为月数
df['diff_day'].astype('timedelta64[M]').head(5)
0    66.0
1    78.0
2    78.0
3    65.0
4    65.0
Name: diff_day, dtype: float64
# 转换为年数
df['diff_day'].astype('timedelta64[Y]').head(5)
0    5.0
1    6.0
2    6.0
3    5.0
4    5.0
Name: diff_day, dtype: float64
# 转换为小时
# 还可转换为分钟、秒等等
df['diff_day'].astype('timedelta64[h]').head(5)
0    48838.0
1    57070.0
2    57070.0
3    48022.0
4    47758.0
Name: diff_day, dtype: float64
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若尘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值