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:

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

Previous: How to convert a Pandas series to a NumPy array and print it?
Next: How to convert a Pandas DataFrame to a NumPy array and back?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/convert-a-numpy-array-to-a-pandas-series-and-print.php