简体   繁体   English

在分组的 pandas 数据帧中创建两个移位列

[英]Creating two shifted columns in grouped pandas data-frame

I have looked all over and I still can't find an example of how to create two shifted columns in a Pandas Dataframe within its groups.我已经查看了所有内容,但仍然找不到如何在其组内的 Pandas Dataframe 中创建两个移位列的示例。

I have done it with one column as follows:我用一列完成了它,如下所示:

data_frame['previous_category'] = data_frame.groupby('id')['category'].shift()

But I have to do it with 2 columns, shifting one upwards and the other downwards.但我必须用 2 列来完成,一列向上移动,另一列向下移动。

Any ideas?有任何想法吗?

It is possible by custom function with GroupBy.apply , because one column need shift down and second shift up:可以通过使用GroupBy.apply自定义 function 来实现,因为一列需要向下移动,第二列需要向上移动:

df = pd.DataFrame({
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'F':list('aaabbb')
})

def f(x):
    x['B'] = x['B'].shift()
    x['C'] = x['C'].shift(-1)
    return x

df = df.groupby('F').apply(f)
print (df)
     B    C  F
0  NaN  8.0  a
1  4.0  9.0  a
2  5.0  NaN  a
3  NaN  2.0  b
4  5.0  3.0  b
5  5.0  NaN  b

If want shift same way only specify all columns in lists:如果想以相同的方式移动,只需指定列表中的所有列:

df[['B','C']] = df.groupby('F')['B','C'].shift()
print (df)
     B    C  F
0  NaN  NaN  a
1  4.0  7.0  a
2  5.0  8.0  a
3  NaN  NaN  b
4  5.0  4.0  b
5  5.0  2.0  b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM