w3resource

How to convert a Pandas series to a NumPy array and print it?


11. Series to Array Conversion

Write a NumPy program to convert a Pandas Series to a NumPy array and print the array.

Sample Solution:

Python Code:

import pandas as pd
import numpy as np

# Create a Pandas Series
series = pd.Series([10, 20, 30, 40, 50])
print("Original Pandas Series:",series)
print("Type:",type(series))
# Convert the Pandas Series to a NumPy array
array = series.to_numpy()
print("\nPandas Series to a NumPy array:")
# Print the NumPy array
print(array)
print("Type:",type(array))

Output:

Original Pandas Series: 0    10
1    20
2    30
3    40
4    50
dtype: int64
Type: <class 'pandas.core.series.Series'>

Pandas Series to a NumPy array:
[10 20 30 40 50]
Type: <class 'numpy.ndarray'>

Explanation:

  • Import Pandas and NumPy Libraries: Import the Pandas and NumPy libraries to work with Series and arrays.
  • Create Pandas Series: Define a Pandas Series with some example data.
  • Convert to NumPy Array: Use the to_numpy() method of the Pandas Series to convert it into a NumPy array.
  • Print NumPy Array: Output the resulting NumPy array to verify the conversion.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a Pandas Series with date-time indices into a NumPy array and extract the year from each element.
  • Write a Numpy program to convert a Pandas Series of categorical data into a NumPy array using label encoding.
  • Write a Numpy program to convert a large Pandas Series to a NumPy array and perform vectorized operations to standardize its values.
  • Write a Numpy program to convert a Pandas Series with missing values into a NumPy array and impute missing data using interpolation.

Go to:


Previous: How to convert a 2D NumPy array to a nested Python list and print it?
Next: How to convert a NumPy array to a Pandas series and print it?

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.