python - 根据条件检索具有最高值的行

标签 python python-3.x pandas dataframe

我有一个如下所示的数据框:

| Id | Label | Width |
|----|-------| ------|
| 0  |   A   |   5   |
| 0  |   A   |   3   |
| 0  |   B   |   4   |
| 1  |   A   |   7   |
| 1  |   A   |   9   |

我想编写一个函数,获取具有相同 id 和标签 A 的行并根据最大宽度对其进行过滤

因此应用该函数后数据框将是:

| Id | Label | Width |
|----|-------| ------|
| 0  |   A   |   5   |
| 0  |   B   |   4   |
| 1  |   A   |   9   |

最佳答案

让我们尝试一下:

m = df['Label'].eq('A')
df_a = df.loc[df[m].groupby(['Id', 'Label'])['Width'].idxmax()]

df_out = pd.concat([df[~m], df_a]).sort_index()

详细信息:

使用 .eq 创建 bool 掩码指定 Label 等于 A 的条件:

>>> m

0     True
1     True
2    False
3     True
4     True
Name: Label, dtype: bool

使用上述掩码过滤行,并根据IdLabel对该数据帧进行分组,并使用idxmax聚合Width > 获取最大值的索引:

>>> df[m].groupby(['Id', 'Label'])['Width'].idxmax().tolist()
[0, 4]

>>> df_a

   Id Label  Width
0   0     A      5
4   1     A      9

最后concat上面的数据帧与包含除A之外的标签的数据帧,并对索引进行排序以维持顺序:

>>> df_out

   Id Label  Width
0   0     A      5
2   0     B      4
4   1     A      9

关于python - 根据条件检索具有最高值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66194784/

相关文章:

python - 从 python 调用 C++ 函数并获取返回值

python - Randrange 依赖于变量 - Python

mysql - Python3 从 MySQL 比较中提取日期无法正常工作

python - 无法让我的脚本有条件地等待

Python限定组合

python - Pandas 将 mysql int 转换为 float64

python - 按另一个数据框中的日期过滤数据框

python - 如何在 Tensorflow 中仅使用 Python 制作自定义激活函数?

python - 如何从 pypi 安装软件包到 anaconda?

python - 使用 pandas 和 Python 删除重复项