如何在熊猫的数据框中按行分组

时间:2019-11-07 01:11:06

标签: pandas

我有一个数据框,我想将它们分组为每组1000行,然后我想找到每个组的最大值和最小值,最后将每个组的最小值和最大值行保存在新的数据框中。

我尝试了各种选择,但是没有运气。我对熊猫很天真。

df.groupby(df['col_name'] // 1000).apply(max) 

另一个是

k = 1000 
res = df.col_name[::-1].rolling(k,1).max().shift(1)[::-1]

pd.concat([df.col_name, res], axis = 1)

enter image description here

如果上面是我的数据框,并且假设我希望每组3行。新数据框应为:

enter image description here

1 个答案:

答案 0 :(得分:0)

使用groupbystack

df.groupby(df.index//3).agg(['first', 'last']).stack().reset_index(drop=True)