Create a pandas series from a dictionary of values and an ndarray
In this tutorial, we will get to know how to create a Pandas Series from Dictionary or Numpy array in Python. I will also tell you what sets the Pandas Series apart from all other data types.
Pandas Series
Series built using the Pandas library are similar to the 1-D arrays, which means they are one-dimensional and can store any data type. The extra feature they come with that sets them apart is the Labeled axis
. This is a built-in feature in the Pandas Series. Labeled Axis means that the indices are labeled in the output. Let me show you the output so that you can better understand it.
From ndarray
A ndarray basically means the n-dimensional array. The important point that you need to know is that Numpy Arrays can be n-dimensional, but series are always one-dimensional. So, if you want to convert the n-dimensional array into a series, first, you will have to flatten it to become one-dimensional.
import numpy as np import pandas as pd my_array = np.array([10, 20, 30, 40, 50]) print("Array output") print(my_array) print("\nSeries Output") series = pd.Series(my_array) print(series)
Array output [10 20 30 40 50] Series Output 0 10 1 20 2 30 3 40 4 50 dtype: int64
Observe both outputs. Now you can see the difference and would have understood the Labeled axis feature.
If you are using a 2D array or nD array, use the function array_name.flatten()
to convert it into 1D array then use the pd.Series()
function.
From Dictionary
When converting the Dictionary to Pandas Series, the key values become the index of the Series.
import pandas as pd data = {'Uttar Pradesh': 'Lucknow', 'Uttarakhand': "Dehradun", 'Madhya Pradesh': "Bhopal", 5: 25} my_series = pd.Series(data) print(my_series)
Uttar Pradesh Lucknow Uttarakhand Dehradun Madhya Pradesh Bhopal 5 25 dtype: object
Leave a Reply