根据不同的列值选择多行

Selecting multiple rows based on different column values

我正在尝试根据分类评估一些图像。我使用下面的代码来读取 csv 文件:

import pandas as pd
file = pd.read_csv('test.csv', header=None)

所以我有一些看起来像这样的东西:

Image1  2  3  4  5  Green
Image1  3  4  5  6  Red
Image2  4  5  6  7  Red
Image3  1  4  8  9  Green
Image4  5  3  0  1  Yellow
Image4  6  2  1  1  Green

因此,如果我想保留值为“绿色”的图像,输出应如下所示:

Image1  2  3  4  5  Green
Image1  3  4  5  6  Red
Image3  1  4  8  9  Green
Image4  5  3  0  1  Yellow
Image4  6  2  1  1  Green

这意味着我想在第一列中保留具有相同 ID 的图像,但至少有一个图像包含我检查的元素在最后一列中。

我使用了 isin 方法,但我不知道如何将图像保留在最后一列中至少按时具有值“绿色”的图像的其余行。

您可以使用 loc 在第 6 列为 Green 的第一列中查找值,并将其用作您的值以传递给 isin:

df[df[0].isin(df.loc[df[5] == "Green", 0])]
# if it has to be the last column, instead of the 6h column, use `iloc` instead:
# df[df[0].isin(df.loc[df.iloc[:, -1] == "Green", 0])]

Image1  2  3  4  5  Green
Image1  3  4  5  6  Red
Image3  1  4  8  9  Green
Image4  5  3  0  1  Yellow
Image4  6  2  1  1  Green

分解:

内部loc检索第一列中包含Green的图像:

df.loc[df[5] == "Green", 0] 
0    Image1
3    Image3
5    Image4
Name: 0, dtype: object

将其传递给 isin,您将获得一个布尔掩码,其中第一列与其中一个值匹配:

df[0].isin(df.loc[df[5] == "Green", 0])
0     True
1     True
2    False
3     True
4     True
5     True
Name: 0, dtype: bool

您可以使用它来过滤您的 df:

df[df[0].isin(df.loc[df[5] == "Green", 0])]

我们可以在这里使用 GroupBy.any,在这里我们检查是否有任何行满足我们的条件:

df[df[5].eq("Green").groupby(df[0]).transform("any")]

        0  1  2  3  4       5
0  Image1  2  3  4  5   Green
1  Image1  3  4  5  6     Red
3  Image3  1  4  8  9   Green
4  Image4  5  3  0  1  Yellow
5  Image4  6  2  1  1   Green