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

2024-10-03 09:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文


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

Tags: columnsthe数据dataindexvalue条目max
1条回答
网友
1楼 · 发布于 2024-10-03 09:13:14

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]

相关问题 更多 >