4.5 C
London
Thursday, December 19, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Convert Pandas Series to NumPy Array (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories