python - 在 Python Pandas 中查找每日最大值及其时间戳 (yyyy:mm:dd hh:mm:ss)
问题描述
实际上,我有 150 MB 的每日分钟测量数据,为期两年。我在这里给出了一个示例数据。我想创建一个新的数据框,每天最多带有时间戳。我的样本数据是:
DateTime Power
01-Aug-16 10:43:00.000 229.9607961
01-Aug-16 10:43:23.000 230.9030781
01-Aug-16 10:44:00.000 231.716212
01-Aug-16 10:45:00.000 232.4485882
01-Aug-16 10:46:00.000 233.2739154
02-Aug-16 09:42:00.000 229.6851724
02-Aug-16 09:43:00.000 230.9163998
02-Aug-16 09:43:06.000 230.9883337
02-Aug-16 09:44:00.000 231.2569098
02-Aug-16 09:49:00.000 229.5774805
02-Aug-16 09:50:00.000 229.8758693
02-Aug-16 09:51:00.000 229.9825204
03-Aug-16 10:09:00.000 231.3605982
03-Aug-16 10:10:00.000 231.6827163
03-Aug-16 10:11:00.000 231.1580262
03-Aug-16 10:12:00.000 230.4054286
03-Aug-16 10:13:00.000 229.6507959
03-Aug-16 10:13:02.000 229.6268353
03-Aug-16 10:14:00.000 230.4584964
03-Aug-16 10:15:00.000 230.9004206
03-Aug-16 10:16:00.000 231.189036
我现在的代码是:
max_per_day = df.groupby(pd.Grouper(key='time',freq='D')).max()
print(max_per_day)
我目前的输出是:
time
2016-08-01 237.243835
2016-08-02 239.658539
2016-08-03 237.424683
2016-08-04 236.790695
2016-08-05 240.163910
目前它输出 yyyy:mm:dd 和值。但我什至希望 hh:mm (或 hh:mm:ss)针对每个最大值。我尝试了以下代码:
max_pmpp_day = df.loc[df.groupby(pd.Grouper(freq='D')).idxmax().iloc[:,0]]
输出是:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
我试过@jezrael 回答
df['DateTime'] = pd.to_datetime(df['time'])
s = df.groupby(pd.Grouper(key='DateTime', freq='D'))['Pmpp'].transform('max')
df = df[df['Pmpp'] == s]
print(df)
输出是
time Pmpp DateTime
34 2016-08-01 11:11:00 237.243835 2016-08-01 11:11:00
434 2016-08-02 13:30:02 239.658539 2016-08-02 13:30:02
648 2016-08-03 12:39:00 237.424683 2016-08-03 12:39:00
解决方案
您可以在新列中使用GroupBy.transform
或Resampler.transform
返回max
值Series
并与原始列进行比较:
df['DateTime'] = pd.to_datetime(df['DateTime'])
s = df.groupby(pd.Grouper(key='DateTime', freq='D'))['Power'].transform('max')
#alternative
#s = df.resample('D', on='DateTime')['Power'].transform('max')
df = df[df['Power'] == s]
print (df)
DateTime Power
4 2016-08-01 10:46:00 233.273915
8 2016-08-02 09:44:00 231.256910
13 2016-08-03 10:10:00 231.682716
或在检查后创建DatetimeIndex
并添加列:groupby
idxmax
df['DateTime'] = pd.to_datetime(df['DateTime'])
df = df.set_index('DateTime')
df = df.loc[df.groupby(pd.Grouper(freq='D'))['Power'].idxmax()]
print (df)
Power
DateTime
2016-08-01 10:46:00 233.273915
2016-08-02 09:44:00 231.256910
2016-08-03 10:10:00 231.682716
@Jon Clements 的解决方案,谢谢:
df = (df.sort_values('Power')
.groupby(df.DateTime.dt.to_period('D'))
.last()
.reset_index(drop=True))
推荐阅读
- javascript - 为什么 Href 属性不能重定向到相应的“.js”文件?
- assembly - 用移位和循环寄存器替换“and”,结果和输入保持不变
- django - 在 django postgresql 中为不同项目使用相同的数据库表
- javascript - 获取某些下拉选项的价值
- java - REST API 添加子时是否需要检查父子关系
- vue.js - Vuetify v-autocomplete 带有异步建议但本地保存的选择
- amazon-web-services - 限制 lambda 函数的无保留并发
- css - CSS 如果元素悬停而不是元素活动更改
- javascript - ReactJS 排序列表 localCompare 在与 ID 关联的列上抛出错误
- javascript - 在 howler.js 中更改动态声音 src 有问题