pandas GroupBy在索引上找到最大值

时间:2017-11-20 00:26:05

标签: python pandas date group-by pandas-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)

1 个答案:

答案 0 :(得分:4)

带有groupby

levels
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]
相关问题