简体   繁体   English

根据条件查找列值

[英]Find the column value based on condition

I need to find unique name, whose age=2 and and cond=9 using python pandas?我需要使用 python pandas 找到唯一的名称,其年龄 = 2 和 cond = 9?

name姓名 age年龄 cond条件 cc抄送
a一个 2 2 9 9 3 3
b b 2 2 8 8 2 2
c C 3 3 9 9 1 1
a一个 2 2 9 9 6 6

这将找到 age = 2 和 cond = 9 的所有不同行

df.loc[(df['age'] == 2) & (df['cond'] == 9)][['name', 'cc']].drop_duplicates()

The Pandas query function allows for SQL-like queries to filter a data frame. Pandas 查询功能允许类似 SQL 的查询来过滤数据框。 Then use unique() on the results to return the unique name.然后对结果使用 unique() 以返回唯一名称。

rows = df.query('age == 2 and cond == 9')
print(rows["name"].unique())

For more query examples, see here .有关更多查询示例,请参见此处

enter code here one potential solution is to put the columns in a zip() and then iterate through you dataframe like so在此处输入代码一种可能的解决方案是将列放在 zip() 中,然后像这样遍历您的数据框

for name, age, cond in zip(df['name'], df['Age'], df['cond']):
    if(age == 2 and cond ==9):
      print(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM