A Series is like a list with labels for each item. It helps you keep track of data with names, not just positions.
Series as labeled one-dimensional array in Pandas
import pandas as pd # Create a Series with data and optional labels (index) series = pd.Series(data, index=labels) # data: list, array, or scalar values # labels: list of labels for each data item (optional)
If you do not provide labels, pandas will use numbers starting from 0.
Labels can be strings, numbers, or other types, but they must be unique.
import pandas as pd # Example 1: Series with default numeric labels series1 = pd.Series([10, 20, 30]) print(series1)
import pandas as pd # Example 2: Series with custom string labels series2 = pd.Series([5, 15, 25], index=['a', 'b', 'c']) print(series2)
import pandas as pd # Example 3: Empty Series series3 = pd.Series([], dtype=float) print(series3)
import pandas as pd # Example 4: Series with one element and label series4 = pd.Series([100], index=['only']) print(series4)
This program creates a Series with fruit names as labels and quantities as data. It shows how to access, add, and remove items by label.
import pandas as pd # Create a Series with data and labels fruits = ['apple', 'banana', 'cherry'] quantities = [10, 20, 15] # Create Series with quantities and fruit names as labels fruit_series = pd.Series(quantities, index=fruits) print('Original Series:') print(fruit_series) # Access data by label print('\nQuantity of bananas:') print(fruit_series['banana']) # Add a new fruit fruit_series['orange'] = 12 print('\nSeries after adding orange:') print(fruit_series) # Remove a fruit fruit_series = fruit_series.drop('apple') print('\nSeries after removing apple:') print(fruit_series)
Time complexity for accessing or adding items by label is usually O(1) because Series uses a hash map internally.
Space complexity depends on the number of items stored in the Series.
A common mistake is confusing position-based access (like lists) with label-based access. Use series.iloc[] for position and series.loc[] for labels.
Use Series when you want labeled data that behaves like a one-dimensional array. Use DataFrame for two-dimensional labeled data.
A Series is a one-dimensional labeled array in pandas.
It stores data with labels (index) to access items by name.
Series supports easy data selection, addition, and removal by labels.