python - 在条件下使用排序切片 Pandas Dataframe

标签 python pandas dataframe

这对我来说有点棘手。假设我有这个数据框:

Group    Mag    Morph
  1     -21.1     S
  1     -20.3     E
  1     -22.0     E
  2     -18.1     E
  2     -23.6     S
  2     -21.9     S
  3     -19.4     S
  3     -19.1     E

我只想选择最低“Mag”对应于“Morph”的“S”的组(即相同的“组”)。

例如,这里:

  • 在第 1 组中,最低的是 -22.0,对应于“E”变体(因此未参加组),

  • 第 2 组是 -23.6,所以“S”(已选组)

  • 对于第 3 组,-19.4,所以是“S”,所以分组。

因此它会选择

Group    Mag    Morph
  2     -18.1     E
  2     -23.6     S
  2     -21.9     S
  3     -19.4     S
  3     -19.1     E

有人可以帮我吗?

最佳答案

您可以使用 filteridxmin检查每组 Morph 列的值:

print (df.groupby('Group').filter(lambda x: x.loc[x.Mag.idxmin(), 'Morph'] == 'S'))
   Group   Mag Morph
3      2 -18.1     E
4      2 -23.6     S
5      2 -21.9     S
6      3 -19.4     S
7      3 -19.1     E

关于python - 在条件下使用排序切片 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41506821/

相关文章:

python - 运行时错误 : Expected object of scalar type Long but got scalar type Float for argument #2 'mat2' how to fix it?

Python:为什么 IDLE 这么慢?

python - 是否有一种有效的方法来对由特定值标记的行的连续子集求和?

python - 如何使用迭代附加到多级 Pandas 数据框?

python - Pandas 数据框 : swap column headings by index

python - Django 调用 'id' 需要一个数字,但得到字符串

python - 相当于 Python 3 中的 thread.interrupt_main()

python - 按多列对 pandas 数据框进行排序,忽略大小写

python - 从数组中移除异常值的技术

python - 如何计算pandas数据框中从一个数据点到所有其他数据点的欧几里德距离之和?