Python ProgrammingPython Programming

How to get scalar value on a cell using conditional indexing from Pandas DataFrame

Get scalar value of a cell using conditional indexing:

import pandas as pd

df = pd.DataFrame({'Age': [30, 40, 30, 40, 30, 30, 20, 25],
                   'Height': [120, 162, 120, 120, 120, 72, 120, 81],
                   'Score': [4.6, 4.6, 9.0, 3.3, 4, 8, 9, 3],
                   'State': ['NY', 'NY', 'FL', 'AL', 'NY', 'TX', 'FL', 'AL']},
                  index=['Jane', 'Jane', 'Aaron', 'Penelope', 'Jaane', 'Nicky',
                         'Armour', 'Ponting'])

print("\nGet Height where Age is 20")
print(df.loc[df['Age'] == 20, 'Height'].values[0])

print("\nGet State where Age is 30")
print(df.loc[df['Age'] == 30, 'State'].values[0])


C:\python\examples>python example56.py
 
Get Height where Age is 20
120
 
Get State where Age is 30
NY
 
C:\python\examples>