w3resource

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


NumPy: Interoperability Exercise-12 with Solution


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

Sample Solution:

Python Code:

import numpy as np
import pandas as pd

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

Output:

Original NumPy array: [10 20 30 40 50]
Type: <class 'numpy.ndarray'>

NumPy array to a Pandas Series:
0    10
1    20
2    30
3    40
4    50
dtype: int32
Type: <class 'pandas.core.series.Series'>

Explanation:

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

Python-Numpy Code Editor: