Home > front end >  Get info about other columns in same row from pandas search
Get info about other columns in same row from pandas search

Time:03-26

I have a .csv file that looks like the following:

Country Number
United  19
Ireland 17
Afghan  20

My goal is to use python-pandas to find the row with the smallest number, and get the country name of that row.

I know I can use this to get the value of the smallest number. min = df['Number'].min() How can I get the country name at the smallest number?

I couldn't figure out how to put in the variable "min" in an expression.

CodePudding user response:

I would use a combination of finding the min and a iloc

df = pd.DataFrame(data)
min_number = df['Column_2'].min()
iloc_number = df.loc[df['Column_2'] == min_number].index.values[0]
df['Column_1'].iloc[iloc_number]

The only downside to this is if you have multiple countries with the same minimal number, but if that is the case you would have to provide more specs to determine the desired country.

CodePudding user response:

If you expect the minimal value to be unique, use idxmin:

df.loc[df['Number'].idxmin(), 'Country']

Output: Ireland

If you have multiple min, this will yield the first one.

  • Related