python-3.x - 如何在groupy组的第一个值之前获取值

标签 python-3.x pandas numpy pandas-groupby

对我的数据应用 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/

相关文章:

python - 为什么 "median"使用统计包比 "mean"快 2 倍?

Python项目结构,项目主文件导入助手

python - joblib.Parallel 通过卡在 Windows 上的 spyder 运行

python - 如何根据列的百分位数从 DataFrame 中采样?

Python pandas 将 Excel 文件中的多个标题转换为列

python - 用 scipy 反转大型稀疏矩阵

python - 如何在numpy中向量化傅立叶级数部分和

Python 枚举类构造与元类

Python 3.6 安装 pandas 错误 - 未找到 pandas 的匹配分布

python - 如何过滤一个 Numpy 数组,使每个 X 值只有一个 Y 值