Pandas Data Series: Convert a NumPy array to a Pandas series
6. Array to Series
Write a Pandas program to convert a NumPy array to a Pandas series.
Sample NumPy array: d1 = [10, 20, 30, 40, 50]
Sample Solution :
Python Code :
import numpy as np
import pandas as pd
np_array = np.array([10, 20, 30, 40, 50])
print("NumPy array:")
print(np_array)
new_series = pd.Series(np_array)
print("Converted Pandas series:")
print(new_series)
Sample Output:
NumPy array: [10 20 30 40 50] Converted Pandas series: 0 10 1 20 2 30 3 40 4 50 dtype: int64
Explanation:
np.array([10, 20, 30, 40, 50]): This code creates a NumPy array 'np_array' containing a sequence of five integers: [10, 20, 30, 40, 50].
new_series = pd.Series(np_array): This line creates a new Pandas Series object 'new_series' from the NumPy array using the pd.Series() constructor. The resulting Series object will have the same values as the NumPy array, and the default index will be assigned to each element starting from 0 and increasing by 1 for each subsequent element.
For more Practice: Solve these Related Problems:
- Write a Pandas program to convert a multi-dimensional NumPy array to a Series by flattening it.
- Write a Pandas program to convert a NumPy array of dates to a Series and set a datetime index.
- Write a Pandas program to convert a NumPy array to a Series and then replace negative values with their absolute values.
- Write a Pandas program to convert a NumPy array to a Series and then sort the Series based on the array values in ascending order.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to convert a dictionary to a Pandas series.
Next:Write a Pandas program to change the data type of given a column or a Series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.