简体   繁体   中英

Output a single row in pandas to an array

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM