Pandas DataFrame - Convert Row to Numpy Array
Pandas DataFrame - Convert Row to Numpy Array
In Pandas, to convert a row in a DataFrame to a numpy array, you can use to_numpy() method.
Each row of a DataFrame can be accessed as a Series object, and Series objects have a method to_numpy() that returns the numpy array representation of the row (Series object).
The syntax to use to_numpy() method to convert a DataFrame row to a numpy array is
row.to_numpy()
In this tutorial, we will go through some examples, with step by step explanation of how to convert a given row in DataFrame to a Numpy Array.
Examples
1. Convert third row in given DataFrame to numpy array
In this example, we are given a DataFrame in df_input. We have to convert the third row in this DataFrame to a numpy.
Steps
- Given a DataFrame in df_input with three columns 'A', 'B', and 'C', and five rows.
df_input = pd.DataFrame({
'A': [2, 4, 6, 8, 10],
'B': [1, 3, 5, 7, 9],
'C': [10, 20, 30, 40, 50]})
- Select the third row using iloc property, and store it in a variable.
row = df_input.iloc[2]
- Call to_numpy() method on row (Series) object, and store the returned numpy array in a variable row_np_array.
row_np_array = row.to_numpy()
- You may print the numpy array to output using print() function.
print(row_np_array)
Program
The complete program to convert a row in a given DataFrame to a numpy array .
Python Program
import pandas as pd
# Take a DataFrame
df_input = pd.DataFrame({
'A': [2, 4, 6, 8, 10],
'B': [1, 3, 5, 7, 9],
'C': [10, 20, 30, 40, 50]})
# Select row
row = df_input.iloc[2]
# Convert row to numpy array
row_np_array = row.to_numpy()
# Print the numpy array
print(row_np_array)
Output
[ 6 5 30]
The row is returned as a one dimensional numpy array.
Summary
In this Pandas Tutorial, we learned how to convert a given row in a DataFrame to a Numpy Array using to_numpy() method, with examples.