Convert Pandas DataFrame to NumPy Array
The NumPy array is the homogeneous multidimensional array , along with a large collection of high-level mathematical functions to operate on these arrays.Convert pandas dataframe to NumPy array
- Usng to_numpy()
df.to_numpy()
- Using to_records()
df.to_records()
- Using asarray()
np.asarray(df)
Lets craete a DataFrame..
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['TotalMarks'] = [82, 38, 63,22,55,40]
df

TotalMarks
0 82
1 38
2 63
3 22
4 55
5 40
Convert pandas dataframe to NumPy array usng to_numpy()
df.to_numpy()
array([[82],
[38],
[63],
[22],
[55],
[40]], dtype=int64)
Checking Type
type(df.to_numpy())
numpy.ndarray
NumPy array dtype
In the above output you can see the dtype=int64 . You can also provide dtype=int64 as parameters.
df.to_numpy(dtype ='float32')
array([[82.],
[38.],
[63.],
[22.],
[55.],
[40.]], dtype=float32)
Convert pandas dataframe to NumPy array usng to_records()
df.to_records()
rec.array([(0, 82), (1, 38), (2, 63), (3, 22), (4, 55), (5, 40)],
dtype=[('index', '<i8'), ('TotalMarks', '<i8')])
Checking Type
type(df.to_records())
numpy.recarray
Note that this is a recarray rather than an numpy.ndarray. You could move the result in to regular numpy array by calling its constructor as np.array(df.to_records()) .
np.array(df.to_records())
array([(0, 82), (1, 38), (2, 63), (3, 22), (4, 55), (5, 40)],
dtype=(numpy.record, [('index', '<i8'), ('TotalMarks', '<i8')]))
Checking Type
type(np.array(df.to_records()))
numpy.ndarray
Convert pandas dataframe to NumPy array usng asarray()
np.asarray(df)

array([[82],
[38],
[63],
[22],
[55],
[40]], dtype=int64)
Checking Type
type(np.asarray(df))
numpy.ndarray
df.values and df.as_matrix()
You can use df.values and df.as_matrix() to convert dataframe to NumPy array. But these two methods are depreciated. If you visit the v0.24 docs for .values, you will see a big red warning that says:
Warning: We recommend using DataFrame.to_numpy() instead.
Related Topics
- Pandas DataFrame: GroupBy Examples
- Pandas DataFrame Aggregation and Grouping
- How to Sort Pandas DataFrame
- Pandas DataFrame: query() function
- Finding and removing duplicate rows in Pandas DataFrame
- How to Replace NaN Values With Zeros in Pandas DataFrame
- How to read CSV File using Pandas DataFrame.read_csv()
- How to shuffle a DataFrame rows
- Import multiple csv files into one pandas DataFrame
- Create new column in DataFrame based on the existing columns
- New Pandas dataframe column based on if-else condition
- How to Convert a Dictionary to Pandas DataFrame
- Rename Pandas columns/index names (labels)