How to Convert Pandas Series to NumPy Array (With Examples)


You can use the following syntax to convert a pandas Series to a NumPy array:

seriesName.to_numpy()

The following examples show how to use this syntax in practice.

Example 1: Convert Series to NumPy Array

The following code shows how to convert a pandas Series to a NumPy array:

import pandas as pd
import numpy as np

#define series
x = pd.Series([1, 2, 5, 6, 9, 12, 15])

#convert series to NumPy array
new_array = x.to_numpy() 

#view NumPy array
new_array

array([ 1,  2,  5,  6,  9, 12, 15])

#confirm data type
type(new_array)

numpy.ndarray

Using the type() function, we confirm that the pandas Series has indeed been converted to a NumPy array.

Example 2: Convert DataFrame Column to NumPy Array

The following code shows how to convert a column in a pandas DataFrame to a NumPy array:

import pandas as pd
import numpy as np

#define DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#convert 'points' column to NumPy array
new_array = df['points'].to_numpy() 

#view NumPy array
new_array

array([25, 12, 15, 14, 19, 23, 25, 29])

#confirm data type
type(new_array)

numpy.ndarray

We can use dtype() to check the data type of the new NumPy array as well:

#check data type
new_array.dtype

dtype('int64')

We can see that the new NumPy array is an integer.

Additional Resources

How to Convert Pandas DataFrame to NumPy Array
How to Convert Pandas DataFrame to List
How to Convert a Dictionary to Pandas DataFrame

Leave a Reply

Your email address will not be published.