SunnyBoiz
SunnyBoiz

Reputation: 594

Pandas retrieve a value based on index

Been trying to search for this but somehow can't seem to find the right answer.

Given the following simple dataframe:

   country   continent    population
0    UK       Europe        111111
1   Spain     Europe        222222
2   Malaysia   Asia         333333
3    USA      America       444444

How can I retrieve the country value if I have a condition WHERE an index value is given? For example, If I am given an index value of 2, I should return Malaysia.

Edit: Forget to mention that the input index value comes from a variable (think of it as a user select a particular row and the selected row provide an index value variable).

Thank you.

Upvotes: 0

Views: 238

Answers (2)

alivne
alivne

Reputation: 478

df.iloc[2]['country']

iloc is used for selection by position, see pandas.DataFrame.iloc documentation for further options.

Upvotes: 1

NYC Coder
NYC Coder

Reputation: 7594

index = 2    
print(df.iloc[index]['country'])

Malaysia

Upvotes: 0

Related Questions