Search code examples
pandasdataframeseries

How can I extract a row from a DataFrame as a Series, with the column names in the DataFrame as the row indices in the Series?


Suppose I have the following dataframe:

   x y z
a  0 1 2
b  3 4 5
c  6 7 8

How can I extract, say, row b as a Series such that I now have:

x 3
y 4
z 5

Solution

  • loc will return a Series when you give it a single label.

    import pandas as pd
    
    df = pd.DataFrame({'x': [0, 3, 6],
                       'y': [1, 4, 7],
                       'z': [2, 5, 8]},
                      index=['a', 'b', 'c'])
    
    s = df.loc['b']
    print(type(s))
    print(s)
    

    Output:

    <class 'pandas.core.series.Series'>
    x    3
    y    4
    z    5
    Name: b, dtype: int64