w3resource

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


12. Array to Series Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a 1D NumPy array into a Pandas Series with a custom index and sort the series by index.
  • Write a Numpy program to convert a NumPy array to a Series and then apply a rolling window function to compute moving averages.
  • Write a Numpy program to convert a structured NumPy array into a Pandas Series with multi-level indices.
  • Write a Numpy program to convert a NumPy array to a Series and then reindex it to include additional missing values.

Go to:


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?

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.