Python - Create a pandas series from a scalar value

By IncludeHelp Last updated : January 11, 2024

A scalar value is just a simple value that only has one component to it i.e., the magnitude. For example, 5 is a scalar value.

Problem statement

Given a scalar value, write Python code to create a Pandas series from it.

Creating a series from a scalar value

To create a pandas series from a scalar value, you can use the pandas.Series() method and pass the value in it.

Python program to create a series from a scalar value

# importing module
import pandas as pd

# creating a variable with scalar value
value = 5

# creating series from a scalar value
series = pd.Series(value)

# printing series
print(series)

Output

The output of the above program is:

0    5
dtype: int64

Creating a series from a scalar value with indexes

You can also specify the indexes during creating a series from a scalar value. To assign indexes to a series, pass the indexes to the index attribute inside pandas.Series() method.

Python program to create a series from a scalar value with indexes

# importing module
import pandas as pd

# creating a variable with scalar value
value = 5

# creating series from a scalar value
series = pd.Series(value, index=[101])

# printing series
print(series)

Output

The output of the above program is:

101    5
dtype: int64

Creating a series of different data type from a scalar value

You can also specify the data type of the output series while creating a series from a scalar value. 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 a scalar value

# importing module
import pandas as pd

# creating a variable with scalar value
value = 5

# creating series from a scalar value
series = pd.Series(value, dtype="float")

# printing series
print(series)

Output

The output of the above program is:

0    5.0
dtype: float64

Giving a name to the series created from a scalar value

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 a scalar value and give a name to it

# importing module
import pandas as pd

# creating a variable with scalar value
value = 5

# creating series from a scalar value
series = pd.Series(value, dtype="float", name="my_series")

# printing series
print(series)

Output

The output of the above program is:

0    5.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 »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.