The efficient and easiest way to convert Numpy Array to Pandas Series is by using pd.Series() constructor. It accepts an array as an argument and returns a Series object. Ensure that the array is single-dimensional and not multi-dimensional.
What is the need for conversion?
- The primary difference between the numpy array and the pandas series is that numpy, by default, indexes each value by integer indices, whereas in pandas, you can explicitly define labels, which can be of type integer or string or any other immutable type. Lable indexing is helpful to access the data from the collection compared to integer indexing.
- Pandas objects can easily align the data based on their indices, whereas numpy objects lack this feature.
- Series can easily manage NaN values where Numpy objects have limited support for it.
The process of conversion
When we convert an array to a series, pd.Series() constructor will create a new Series object in the memory. It is a different object from an array object.
Then, the data is copied from the array to that object, and now the Series is an independent object with its own data.
While creating a new Series object, if you don’t specify the labels, it will create its own RangeIndex to assign an index to each element.
Example
import numpy as np import pandas as pd # Creating an nd array object numpy_array = np.array([11, 21, 31, 41, 51]) print(numpy_array) print(type(numpy_array)) # Converting the NumPy array to a Pandas Series pandas_series = pd.Series(numpy_array) # Printing the Pandas Series print(pandas_series) # Printing the series object type print(type(pandas_series))
Output
You can see in the above code that the numpy array’s type is “<class ‘numpy.ndarray’>” and after the conversion, we have a Series whose type is “<class ‘pandas.core.series.Series’>”.
Converting 2D Numpy Array to Series
You cannot convert a 2D numpy array to a Series because the Series itself is not a multi-dimensional object. A Series is a single-dimensional labeled array.
If you want to get with 2D Pandas object with rows and columns, I would recommend you convert it into a Pandas DataFrame.
If you are stubborn like me and still want to convert it into a Series, then you have to flatten the 2D array into a 1D array and then use pd.Series() method to get Series.
import numpy as np import pandas as pd arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Flatten the array arr_1d = arr_2d.flatten() # Convert to Series series = pd.Series(arr_1d) print(series) print(type(series))
Output
That’s all!