Home > front end >  Find the column value based on condition
Find the column value based on condition

Time:06-25

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

CodePudding user response:

This will find all distinct rows where age = 2 and cond = 9

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

CodePudding user response:

The query function allows for SQL-like queries to filter a data frame. Then use unique() to return the unique name from the results.

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

For more examples, can find query examples here.

CodePudding user response:

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)
  • Related