Search code examples
pythonpandasdataframerow

Python: Pandas Dataframe select row by given index


I have a pandas dataframe of this kind:

data = {'Index':[1a,2a,3a,4a], 'col1':[20.1,20.2,20.3,20.4], 'col2': [30.2,30.5,30.7,30.5]}
df1 = pd.DataFrame(data)
df1 = df1.set_index('Index')
print(df1)

output:

        col1  col2
Index            
1a      20.1  30.2
2a      20.2  30.5
3a      20.3  30.7
4a      20.4  30.5

Now my aim is to select the row with a specific index, say 2a, so the output should be:

        col1  col2
Index            
2a      20.2  30.5

I tried it with following command (see e.g. this tutorial):

df1.loc[df1['Index'] == 2]

but for some reason it does not work, why?


Solution

  • Just use .loc:

    >>> df.loc['2a']
    col1    20.2
    col2    30.5
    Name: 2a, dtype: float64
    
    >>> df.loc['2a', 'col1']
    20.2