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:
a | b | c |
---|---|---|
1 | 2 | 3 |
4 | 5 | 6.5 |
7 | 8.5 | 9 |
10 | 11 | 12 |
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
Getting CSV File Link
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

If you're thinking about taking a trip to the United States, you might consider exchanging some of your money into U.S. dollars, which is the official currency of the country. The international symbol for the currency is USD.USD is also the official currency in a few other countries, including Ecuador

If you're considering a journey to the United States, it might be beneficial to convert some of your money into U.S. dollars, which is the official currency of the country. The internationally recognized symbol for this currency is USD.Additionally, USD serves as the official currency in Ecuador and El

Utilize our inch-to-fraction calculator to effortlessly perform conversions between inch fractions, decimal values, metric measurements, and feet. Effective Techniques for Calculating Inch FractionsInches can be represented as fractions or decimals. When dealing with inch fractions, it is vital to

Please enter the necessary values below to convert kilowatts [kW] to British thermal units per hour [Btu/h], or the other way around.Description: A kilowatt (symbol: kW) is a unit of power within the International System of Units (SI). The watt, after the Scottish inventor James Watt, serves as the base