如果我有这样一个数据帧:
category name index
A A11 1
A A12 1
A A13 1
A A21 2
A A22 2
A A23 2
...
B B11 1
B B21 2
...
我想首先根据category和index对dataframe进行分组,在每个组中,我想将name
列按index的值进行移位(反向移位)-1。你知道吗
结果是:
category name index
A A11 1 # Do not shift anything because index is 1
A A12 1
A A13 1
A A22 2 # Shift -1 for anything in (A, 2) group because index here is 2
A A23 2
A A24 2
...
B B11 1
B NA 2 # at the end of each group it should be NA
我尝试过使用.groupby()和.apply(),但似乎没有简单的方法将结果连接回数据帧。似乎apply方法只能返回一个序列。如何使用apply方法实现这一点?你知道吗
如果我理解正确,我认为你可以这样做:
给定df
使用query筛选索引不是1的数据帧,然后在
groupby
内移动,并将索引等于1的筛选器数据帧的concat部分移动到移位的数据帧。你知道吗输出:
如果我理解你的问题
相关问题 更多 >
编程相关推荐