Q:

How to convert pandas DataFrame to NumPy array?

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to check if any value is NaN in a Pandas DataF... >>
<< How to avoid Pandas creating an index in a saved C...