pandas 对索引进行分组并找到最大值

pandas GroupBy on the index and find the max


我有一个大数据框(大约 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)

groupbylevels

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

The next two options require the index to be a datetime index. If it isn't, convert it:

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]