对我的数据应用 groupby 后,我想保存一些值。我在数据框中有两列,x1 和 x2。按 x2 列应用 groupby 函数,并从组的第一个值之前的 x1 获取值。
df=pd.DataFrame({'x1':[3,4,5,6,7,8,9,2,7],x2:[1,3,3,3,2,2,2,2]})
x1 x2
0 3 1
1 4 3
2 5 3
3 6 3
4 7 2
5 8 2
6 9 2
7 2 2
8 7 2
desired output:
df_out=pd.DataFrame({'x1_value':[3,6]})
x1_value
0 3
1 6
最佳答案
这是使用 nth
的方法来自pandas 0.25:
df=pd.DataFrame({'x1':[3,4,5,6,7,8,9,2,7],'x2':[1,3,3,3,2,2,2,2,2]})
df.groupby('x2', sort=False).nth(-1)[:-1]
输出:
x1
x2
1 3
3 6
详细信息:
- 按 x2 分组,sort = False
- 使用
nth
获取每组的最后一个值 - 切片以消除最后一组中的最后一个值
关于python-3.x - 如何在groupy组的第一个值之前获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504342/