Convert a Pandas DataFrame to a NumPy array

PandasServer Side ProgrammingProgramming

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

 Live Demo

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:\n", df
print "DataFrame to numpy is:\n", df.to_numpy()
print "DataFrame to numpy is:\n", 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]
raja
Published on 30-Aug-2021 10:00:24
Advertisements