How to create Series in Pandas Python

You can create a series in Pandas Python with the following code. I highly recommend you This book to learn Python. Pandas Series is a one-dimensional array that can store data of any type. A series is like a single column in a table. You will see 7 examples of the Pandas series in this article.

  1. Pandas Series from the List
  2. Pandas Series from the Dictionary
  3. Pandas Series from the NumPy array
  4. Create Empty Series in Pandas
  5. Pandas Series with the specific index
  6. Random Series in Pandas
  7. Copy of the Series in Pandas

Step 1: Install Pandas Library

Install the Pandas library using this code, if it is not installed.

pip install pandas

Pandas Series from the List

# Import the required libraries
import pandas as pd
import numpy as np

# Initialize a list
a = [5, 8, 10, 25, 20, np.nan, 12]

# Create Series
b = pd.Series(a)

# Display the Output
print(b)

Output:

0     5.0
1     8.0
2    10.0
3    25.0
4    20.0
5     NaN
6    12.0
dtype: float64

Pandas Series from the Dictionary

# Import the Pandas library as pd
import pandas as pd

# Initialize a dictionary
dict = {'Countries':['China', 'Russia', 'Japan', 'USA']}

# Create Series
a = pd.Series(dict)

# Display the Output
print(a)

Output:

Countries    [China, Russia, Japan, USA]
dtype: object

Pandas Series from the NumPy array

# Import the Pandas library as pd
import pandas as pd

# Initialize a NumPy array
a = np.array([10, 15, 30, 45, 70])

# Create Series
b = pd.Series(a)

# Display the Output
print(b)

Output:

0    10
1    15
2    30
3    45
4    70
dtype: int32

Create Empty Series in Pandas

# Import the Pandas library as pd
import pandas as pd

# Create Series
a = pd.Series()

# Display the Output
print(a)

Output:

Series([], dtype: float64)

Pandas Series with the specific index

# Import the Pandas library as pd
import pandas as pd

# Initialize a NumPy array
a = np.array([30, 5, 50, 65, 73])

# Create Series
b = pd.Series(a, index=['A', 'B', 'C', 'D', 'E'])

# Display the Output
print(b)

Output:

A    30
B     5
C    50
D    65
E    73
dtype: int32

Random Series in Pandas

# Import the required libraries
import pandas as pd
import numpy as np

# Create a random array of integers from 0 to 100
a = np.random.randint(0,100 ,size = 10)

# Create a Series
b = pd.Series(a)

# Display the Output
print(b)

Output:

0    19
1    24
2     7
3     3
4    72
5     0
6    77
7    91
8    19
9    71
dtype: int32

Copy of the Series in Pandas

# Import the Pandas library as pd
import pandas as pd

a = pd.Series([11, 12, 13, 44, 65])

# Display the Original Series
print(a)

# Make a copy of series
b = a.copy()

# Display the Copy of Series
print(b)

Output:

0    11
1    12
2    13
3    44
4    65
dtype: int64
0    11
1    12
2    13
3    44
4    65
dtype: int64

Free Learning Resources

Leave a Comment

Your email address will not be published.