1.

How do you convert Pandas DataFrame to a NumPy array?

Answer»

The to_numpy() method of the NumPy package can be used to convert Pandas DataFrame, Index and Series objects.

Consider we have a DataFrame df, we can either convert the whole Pandas DataFrame df to NumPy array or even select a subset of Pandas DataFrame to NumPy array by using the to_numpy() method as shown in the example below:

import pandas as pd
import numpy as np
# Pandas DataFrame
df = pd.DataFrame(data={'A': [3, 2, 1], 'B': [6,5,4], 'C': [9, 8, 7]},
index=['i', 'j', 'k'])
print("Pandas DataFrame: ")
print(df)

# Convert Pandas DataFrame to NumPy Array
np_arr = df.to_numpy()
print("Pandas DataFrame to NumPy array: ")
print(np_arr)


# Convert specific columns of Pandas DataFrame to NumPy array
arr = df[['B', 'C']].to_numpy()
print("Convert B and C columns of Pandas DataFrame to NumPy Array: ")
print (arr)

The output of the above code is

Pandas DataFrame:
A B C
i 3 6 9
j 2 5 8
k 1 4 7
Pandas DataFrame to NumPy array:
[[3 6 9]
[2 5 8]
[1 4 7]]
Convert B and C columns of Pandas DataFrame to NumPy Array:
[[6 9]
[5 8]
[4 7]]


Discussion

No Comment Found