在 Pandas 中汇总日期时间数据

在 Python 中处理日期和时间

Max Shron

Data Scientist and Author

在 Pandas 中汇总数据

# 平均离桩时间
rides['Duration'].mean()
Timedelta('0 days 00:19:38.931034482')
# 总离桩时间
rides['Duration'].sum()
Timedelta('3 days 22:58:10')
在 Python 中处理日期和时间

在 Pandas 中汇总数据

# 离桩时间占比
rides['Duration'].sum() / timedelta(days=91)
0.04348417785917786
在 Python 中处理日期和时间

在 Pandas 中汇总数据

# 统计每个会员类型的次数
rides['Member type'].value_counts()
Member 236
Casual  54
Name: Member type, dtype: int64
# 各会员类型的骑行占比
rides['Member type'].value_counts() / len(rides)
Member 0.814 
Casual 0.186 
Name: Member type, dtype: float64
在 Python 中处理日期和时间

在 Pandas 中汇总日期时间

# 添加时长(秒)列
rides['Duration seconds'] = rides['Duration'].dt.total_seconds()

# 各会员类型的平均时长 rides.groupby('Member type')['Duration seconds'].mean()
Member type 
Casual 1994.667 
Member 992.280 
Name: Duration seconds, dtype: float64
在 Python 中处理日期和时间

在 Pandas 中汇总日期时间

# 按月的平均时长
rides.resample('ME', on = 'Start date')['Duration seconds'].mean()
  • 常用频率:D(日)、W(周)、ME(月末)、YE(年末)
Start date 
2017-10-31 1886.454 
2017-11-30 854.175 
2017-12-31 635.101 
Freq: ME, Name: Duration seconds, dtype: float64
在 Python 中处理日期和时间

在 Pandas 中汇总日期时间

# 每组的数量
rides.groupby('Member type').size()
Member type
Casual     54
Member    236
dtype: int64
# 每组的第一条骑行
rides.groupby('Member type').first()
            Duration     ...     
Member type              ...
Casual      02:07:02     ...        
Member      00:03:01     ...
在 Python 中处理日期和时间

在 Pandas 中汇总日期时间

rides\
  .resample('ME', on = 'Start date')\
  ['Duration seconds']\
  .mean()\
  .plot()

在 Python 中处理日期和时间

在 Pandas 中汇总日期时间

rides\
  .resample('D', on = 'Start date')\
  ['Duration seconds']\
  .mean()\
  .plot()

在 Python 中处理日期和时间

在 Pandas 中汇总日期时间数据

在 Python 中处理日期和时间

Preparing Video For Download...