Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Convert a Pandas DataFrame to a NumPy array
To convert a Pandas DataFrame to a NumPy array, we can use to_numpy().
Steps
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame.
Print the NumPy array of the given array, using df.to_numpy().
Print the NumPy array of the given array for a specific column, using df['x'].to_numpy().
Example
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:
", df
print "DataFrame to numpy is:
", df.to_numpy()
print "DataFrame to numpy is:
", df['x'].to_numpy()
Output
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 DataFrame to numpy is: [[ 5 4 4] [ 2 1 1] [ 1 5 5] [ 9 10 0]] DataFrame to numpy is: [5 2 1 9]
Advertisements
