python - 根据不同的列值选择多行
问题描述
我正在尝试根据分类评估一些图像。我使用下面的代码来读取 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
因此,如果我想保留值为“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])]
推荐阅读
- sql - ORACLE 数据库如何将 DATE 隐式转换为 NUMBER?
- python - UnicodeDecodeError 或无法识别的结果
- node.js - 部署 Angular 9 应用程序
- jquery-ui - 为表中的每一行创建 jQuery ui 对话框
- android - 显示错误:从 android 中的任务运行签名报告时缺少密钥库
- python - 在 Python3 中混合使用 Parallel 和 subprocess,导致 CPU 效率随着时间的推移而降低?
- css - 谷歌浏览器在按钮用户代理样式的焦点状态上显示黑色边框
- java - Mule 4:内存管理:如果传递的参数太大,mule 中会发生 stackoverflowerror 吗?
- sfml.net - SFML C# 如何在全屏之间切换?
- c# - 如何定义第二个实体框架核心关系到同一个外键?