ADVERTISEMENT
ADVERTISEMENT

How to convert pandas DataFrame to NumPy array?

Learn How to convert pandas DataFrame to NumPy array?
Submitted by Pranit Sharma, on April 20, 2022

In python pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data. DataFrame can be created with the help of python dictionaries. Pandas also allow us to convert this DataFrame into a NumPy array using DataFrame.to_numpy() method.

pandas.DataFrame.to_numpy() Method

This method simply takes a DataFrame as a parameter and converts it into NumPy array. The data type of the returned array will be common of all the data types in the DataFrame which is passed as a parameter.

Syntax:

DataFrame.to_numpy(
    dtype=None, 
    copy=False, 
    na_value=NoDefault.no_default
    )

The dtype is the data type passed to the method, apart from dtype, it has two more optional parameters, i.e., copy and na_value.

To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Jarvis":[69,74,77,72],
    "Peter":[65,96,65,86],
    "Harry":[87,97,85,51],
    "Sam":[66,68,85,94]
}

# Now, Create DataFrame
df = pd.DataFrame(d)

# Printing the DataFrame
print("DataFrame:\n",df,"\n\n")

# Converting the DataFrame into NumPy array
arr=df.to_numpy()

# Printing the array
print("Converted NumPy array:\n",arr)

Output:

Convert pandas DataFrame to NumPy array

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.