Output a single row in pandas to an array

15,895

Solution 1

# Dummy DataFrame
df = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]})
# Extract second row (index: 1)
df.iloc[1].values

Solution 2

Since Pandas data is stored internally as Numpy arrays, you can extract the Numpy representation directly.

v0.24+

Use pd.Series.to_numpy method:

df.iloc[3].to_numpy()  # output 4th row as Numpy array

Before v0.24

Use pd.Series.values property:

df.iloc[3].values  # output 4th row as Numpy array

Just remember that if your dataframe contains multiple types, the dtype of the row-wise Numpy array may become object. This will lead to inefficiencies in subsequent operations.

Share:
15,895
thejoker34
Author by

thejoker34

Updated on June 21, 2022

Comments

  • thejoker34
    thejoker34 almost 2 years

    I would like to be able to pull out an arbitrary row, such as the 4th row, and get an array so that I can send it through another function.

    What would be the easiest way to do this?

  • GoPackGo
    GoPackGo almost 3 years
    as_matrix was deprecated since version 0.23.0. Generally, it is recommended to use ‘.values’ as shown below in the accepted answer.