Creating a Series

What is a Series?

A Pandas Series is a one-dimensional labeled array that can hold any data type (integers, strings, floating point numbers, Python objects, etc.).

The Series is similar to a column in a spreadsheet or a single-column DataFrame.

Each element in a Series has an associated label, called the index.

Can think of a Series as a fixed-size dictionary in that you can get and set values by index label:

pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])
a		5.0
b		5.0
c		5.0
d		5.0
e		5.0
dtype: float64
s['a'] # similar to indexing a value from dict, where you pass the key [index]
5.0

Creating a Series

You can create a Pandas Series from various data types, including lists, NumPy arrays, and dictionaries using:

pd.Series(data, index, inplace)
Parameters

Parameters are very similar to that of pd.DataFrame() function. With the exception to the data passed: If data is a scalar value, an index must be provided. The value will be repeated to match the length of index.

Lists

import pandas as pd

# Sample Python list
python_list = [10, 20, 30, 40, 50]

# Creating a Pandas Series from a Python list
series_from_list = pd.Series(python_list) # default int index starting from 0

# Displaying the Series
print(series_from_list)
0    10
1    20
2    30
3    40
4    50
dtype: int64

Dictionaries

Each key-value pair in the dictionary becomes an element in the Series, with keys serving as the index labels.

pd.Series(
		  {'index1':value1,
		  'index1':value1,
		  ...
		  }
)

We can also explicitly specify the index while creating the Series:

import pandas as pd

# Sample dictionary
data_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}

# Creating a Pandas Series from a dictionary with custom index
custom_index_series = pd.Series(data_dict, index=['b', 'a', 'd', 'c'])
custom_index_series = pd.Series(data_dict, index=['b', 'a', 'd', 'c'])

Indexing a Series

Indexing a series follows the usual Python Indexing and Slicing methods.

Powered by Forestry.md