索引上的熊猫 GroupBy 并找到最大值

菲利普·莱莫斯


我有一个大数据框(大约 35k 个条目),该数据框的索引由日期(如2014-02-12)组成,这个日期不是唯一的。我需要做的是为每个数据找到每个数据的最大值并用它创建一个新的数据框。我创建了一个有效的解决方案(如下所示),但需要大量时间来处理。有没有人知道我可以这样做的更快方法?谢谢你。

#Creates a empty dataframe
dataset0514maxrec = pd.DataFrame(columns=dataset0514max.columns.values)
dataset0514maxrec.index.name = 'Date'

#Gets the unique values, find the groups, recover the max value and append it
for i in dataset0514max.index.unique():
    tempDF1 = dataset0514max.loc[dataset0514max.index.isin([i])]
    tempDF2 = tempDF1[tempDF1['Data_Value'] == tempDF1['Data_Value'].max()]
    dataset0514maxrec = dataset0514maxrec.append(tempDF2.head(1))

print(dataset0514maxrec)
cs95

groupbylevels

df.groupby(level=0).Data_Value.max().reset_index()

接下来的两个选项要求索引是datetime索引。如果不是,请转换它:

df.index = pd.to_datetime(df.index) 

resample

df.resample('D').max()

sort_values + duplicated

df = df.sort_values('Data_Value')
m = ~df.index.duplicated()
df = df[m]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章