Home »
Python »
Python Programs
Python - Create a pandas series from an array
By IncludeHelp Last updated : January 11, 2024
Problem statement
Given a NumPy array, write Python code to create a Pandas series from it.
Creating a series from an array
To create a pandas series from an array, you can use the pandas.Series() method and pass a NumPy array in it. To create an array, use the numpy.array() method.
Python program to create a series from an array
# importing modules
import numpy as np
import pandas as pd
# creating an array
arr = np.array([10, 20, 30, 40])
# creating series from an array
series = pd.Series(arr)
# printing series
print(series)
Output
The output of the above program is:
0 10
1 20
2 30
3 40
dtype: int64
Creating a series from an array with indexes
You can also specify the indexes during creating a series from an array. To assign indexes to a series, pass the indexes to the index attribute inside pandas.Series() method.
Python program to create a series from an array with indexes
# importing modules
import numpy as np
import pandas as pd
# creating an array
arr = np.array([10, 20, 30, 40])
# creating series from an array
series = pd.Series(arr, index=[100, 101, 102, 103])
# printing series
print(series)
Output
The output of the above program is:
100 10
101 20
102 30
103 40
dtype: int64
Creating a series of different data type from an array
You can also specify the data type of the output series while creating a series from an array. To specify the data type of the output series, pass the data type with dtype attribute inside pandas.Series() method.
Python program to create a series of different data type from an array
# importing modules
import numpy as np
import pandas as pd
# creating an array
arr = np.array([10, 20, 30, 40])
# creating series from an array
series = pd.Series(arr, dtype="float")
# printing series
print(series)
Output
The output of the above program is:
0 10.0
1 20.0
2 30.0
3 40.0
dtype: float64
Giving a name to the series created from an array
You can also set a name to the output series by specifying the series name with the name attribute inside pandas.Series() method.
Python program to create a series from an array and give a name to it
# importing modules
import numpy as np
import pandas as pd
# creating an array
arr = np.array([10, 20, 30, 40])
# creating series from an array
series = pd.Series(arr, dtype="float", name="my_series")
# printing series
print(series)
Output
The output of the above program is:
0 10.0
1 20.0
2 30.0
3 40.0
Name: my_series, dtype: float64
To understand the above programs, you should have the basic knowledge of the following Python topics:
Python Pandas Programs »