Transform Your Dataframe into a Powerful Numpy Array with Pandas Dataframe.to_numpy() - GeeksforGeeks

AccessInteractLearning ProgramsApplyVideo TutorialsAmeliorate Your Article

Save the Revised Article

Recommend the Article

Pandas DataFrame presents a potentially heterogeneous tabular data structure that is mutable in size and has labeled axes for both rows and columns. By using the DataFrame.to_numpy() functionality, it is viable to transform this data structure into a NumPy ndarray. This article outlines the steps needed to facilitate the conversion of dataframe to numpy array.

Syntax of Pandas DataFrame.to_numpy()

The Syntax is as Follows:  DataFrame.to_numpy(dtype = None, copy = False) 

Parameters: 

dtype: Defines the data type, e.g. str. copy: [bool, default False] Ensures that there is no dependence on another array and that the returned value is a new one.Returns: numpy.ndarray

Converting DataFrame to Numpy Array

In this section, we will concentrate on how to transform a DataFrame to a Numpy array.

import pandas as pd

df = pd.DataFrame(

    [[1, 2, 3],

     [4, 5, 6],

     [7, 8, 9],

     [10, 11, 12]],

    columns=['a', 'b', 'c'])

arr = df.to_numpy()

print('\nNumpy Array\n----------\n', arr)

print(type(arr))

Result:

Numpy Array:

  • ----------
  • The following is a Numpy Array:
  • [[1 2 3]
  • [4 5 6]
  • [7 8 9]
  • [10 11 12]]

Our goal is to transform a specified column into a Numpy Array. To accomplish this, we need to utilize the Python library Pandas. First, we import this library using the following code:

import pandas as pd

After importing Pandas, we create a DataFrame with rows and columns of data. Here is an example of a DataFrame:

  • df = pd.DataFrame([[1, 2, 3],
  • [4, 5, 6],
  • [7, 8, 9],
  • [10, 11, 12]],
  • columns=['a', 'b', 'c'])

Next, we create a Numpy Array from the DataFrame. We choose to select only columns "a" and "c" from the DataFrame to convert into a Numpy Array. We do this using the code:

arr = df[['a', 'c']].to_numpy()

Our Output will be:

  • Numpy Array:
  • ----------
  • [[ 1 3]
  • [ 4 6]
  • [ 7 9]
  • [10 12]]
  • It is useful to note that this specific operation converts a DataFrame with different data types. To be able to perform this procedure, we also import Numpy into our Python script using the following code:
  • import numpy as np

As can be seen from the results, the Numpy Array provides us with a cleaner and more organized display of the specified columns from our Pandas DataFrame. The Numpy Array can be used to further process the data in machine learning or data science applications.

Transforming Data from CSV File to Numpy Array

In this code snippet, we convert data from a CSV file to a Numpy array utilizing pandas. We use the DataFrame.to_numpy() method to convert the data from the CSV file (nba.csv) to a Numpy array.

First, let's take a look at the data that we will convert:

abc
123
456.5
78.59
101112

Converting CSV Data to Numpy Array

Here's the code snippet for converting data from a CSV file to a Numpy array:

import pandas as pd

# Reading data from CSV file

data = pd.read_csv("nba.csv")

# Dropping null values

data.dropna(inplace=True)

# Creating a dataframe and selecting the "Weight" column from the CSV file

df = pd.DataFrame(data['Weight'].head())

# Converting the selected column to a Numpy array

arr = df.to_numpy()

print("Numpy Array:", arr)

print("Numpy Array Datatype:", arr.dtype)

The resulting Numpy array is:

Numpy Array:

180.0
235.0

Numpy Array Datatype: float64

To access the CSV file, click on the following link: nba.csv

Reformatted Code Examples

Illustration 2:

The following code is an illustration where we simply enter the parameters in the same code to present the numpy data type dtype.

import pandas as pd

data = pd.read_csv("nba.csv")

data.dropna(inplace=True)

df = pd.DataFrame(data['Weight'].head())

print(df.to_numpy(dtype='float32'))

Output:

[[180.]

[235.]

[185.]

[235.]

[238.]]

Example 3:

The code below validates the type of the array following conversion.

import pandas as pd

data = pd.read_csv("nba.csv")

data.dropna(inplace=True)

df = pd.DataFrame(data['Weight'].head())

print(type(df.to_numpy()))

Output:

Last Updated :

  • 05 Jan, 2023
  • Like Article
  • Save Article
"Transform Your Gaming Experience with the Top 10 Wii to HDMI Adapters of 2023: A Detailed Reviews and Buying Guide"
"Transform Your Gaming Experience with the Top 10 Wii to HDMI Adapters of 2023: A Detailed Reviews and Buying Guide"

Numerous individuals possess a Wii console but are unable to use it due to improper cables or incompatibility with their TV or monitor. However, you can effortlessly connect a Wii console to any TV utilizing an adapter since all modern TVs and monitors support HDMI connections. Thus, we have

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-06-02 01:43:59
"Upgrade Your Gaming System Now with the Top 5 HDMI Adapters for Wii [2023 Edition]"
"Upgrade Your Gaming System Now with the Top 5 HDMI Adapters for Wii [2023 Edition]"

Do you remember how the Nintendo Wii revolutionized gaming? Its motion controls were a game-changer and the available games, such as Wii Sports, were amazing. But as technology progressed, the Wii became outdated, and playing it nowadays is challenging because of video output compatibility

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-06-02 00:13:36
A Comprehensive Guide to Using TerraMatch
A Comprehensive Guide to Using TerraMatch

The Convert Time Stamps feature can be employed to transform the format of time stamps. A range of conversions are supported, including GPS seconds-of-week to GPS standard time, GPS time to GPS standard time, GPS seconds-of-day to GPS seconds-of-week, Unix time to GPS standard time, UTC seconds-of-day

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-06-02 00:12:09
Unlock the Secret to Transferring Gift Cards to PayPal!
Unlock the Secret to Transferring Gift Cards to PayPal!

Unleash the potential of that neglected gift card by transferring its value to your PayPal account! Not only will you bolster your balance, but you’ll open up a world of spending opportunities. But how does one go about making this shift? Let’s dive into the basics so you can make the move with

Author: Dranky Cowell Author: Dranky Cowell
Posted: 2023-06-01 00:10:31
Showing page 1 of 10

VyConvert - since 2022
, US

Facebook| | DMCA

Gen in 0.1502 secs