Sunday, 24 September 2023

How to Convert a Pandas DataFrame to a NumPy Array?

Dataframe 'to_numpy' method return a numpy array representation of dataframe data.

 

Example

numpy_array = df.to_numpy()

Find the below working application.

 

dataframe_to_numpy_array.py

import pandas as pd

df = pd.DataFrame(
    {
        'name': ['Krishna', 'Ram', 'Thulasi'],
        'age': [34, 35, 39],
        'gender': ['Male', 'Male', 'Female']
    }
)

numpy_array = df.to_numpy()

print(f'df : \n{df}')
print(f'\nnumpy_array : \n{numpy_array}')

Output

df : 
      name  age  gender
0  Krishna   34    Male
1      Ram   35    Male
2  Thulasi   39  Female

numpy_array : 
[['Krishna' 34 'Male']
 ['Ram' 35 'Male']
 ['Thulasi' 39 'Female']]



Previous                                                 Next                                                 Home

No comments:

Post a Comment