简体   繁体   中英

Find the column value based on condition

I need to find unique name, whose age=2 and and cond=9 using python pandas?

name age cond cc
a 2 9 3
b 2 8 2
c 3 9 1
a 2 9 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. Then use unique() on the results to return the unique name.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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