Home > Mobile >  Fetch a column value based on another column value in Pandas
Fetch a column value based on another column value in Pandas

Time:09-01

Got stuck in figuring out extracting a column value based on another column value as I am new to pandas dataframe.

    Name    Age   City 
0   Jim     19    NY
1   Tom     25    LA
2   Sid     33    PH

How to extract Name based on a value for City? ie, to get result as Sid when City = PH

CodePudding user response:

This will work:

name = df[df.City=='PH'].Name.iloc[0]

Alternatively, you can do:

name = df.query("City=='PH'").Name.iloc[0]

Also this:

name = df.loc[df.City=='PH', 'Name'].iloc[0]

And one more:

name = df.set_index('City').Name['PH']

CodePudding user response:

Use:

df.loc[df['City'].eq('PH'), 'Name'].squeeze()

If there is a single 'PH' row, you will get "Sid", else you will have a Series of all available names for which the city is PH.

  • Related