Series
A Series is one column of data with a label, called the index, for every value. A DataFrame is a set of Series that share one index.
import pandas as pd
temps = pd.Series([21.5, 24.0, 19.8, 26.3, 23.1],
index=["Mon", "Tue", "Wed", "Thu", "Fri"],
name="temperature")
print(temps)
print(temps["Thu"]) # by label
print(temps.iloc[0]) # by positionWithout an index, pandas numbers the values 0, 1, 2 and so on.
From a dictionary
import pandas as pd
stock = pd.Series({"apples": 40, "bananas": 25, "cherries": 0, "dates": 12})
print(stock)
print(stock.index.tolist())
print(stock.values)
print("apples" in stock)The keys become the index and the values the data. A Series behaves much like a dictionary: in checks the labels.
Calculating with a Series
import pandas as pd
prices = pd.Series([120, 45, 300, 80], index=["pen", "notebook", "bag", "ruler"])
print(prices * 1.18) # 18% tax on every price at once
print(prices[prices > 100]) # filter with a condition
print(prices.sum(), prices.mean(), prices.max())
print(prices.idxmax()) # the LABEL of the largest valueArithmetic and comparisons work on every value at once, just as with NumPy arrays.
Counting values
import pandas as pd
answers = pd.Series(["yes", "no", "yes", "maybe", "yes", "no"])
print(answers.value_counts())
print(answers.value_counts(normalize=True).round(2))
print(answers.nunique(), "different answers")value_counts is one of the most-used methods in pandas: how many of each value, most common first. With normalize=True, it gives fractions instead of counts.
Labels line up
import pandas as pd
june = pd.Series({"apples": 40, "bananas": 25, "cherries": 10})
july = pd.Series({"bananas": 30, "apples": 35, "dates": 12})
print(june + july)
print(june.add(july, fill_value=0))Arithmetic between two Series matches values by label, not by position, so the apples are added to the apples even though they're in different places. A label found in only one of them gives NaN (missing), unless you supply a fill_value.
loc and iloc
import pandas as pd
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(s.loc["b":"d"]) # by label: the end label IS included
print(s.iloc[1:3]) # by position: like Python slices, the end is excluded
print(s.loc[["a", "c"]])loc selects by label and iloc by position. Prefer them to plain s[...] when the index holds numbers, where it's otherwise unclear which you mean.
Cleaning text
import pandas as pd
names = pd.Series([" asha verma", "LEO KIM ", "mei tanaka"])
clean = names.str.strip().str.title()
print(clean)
print(clean.str.split().str[0]) # first names
print(clean.str.len())The .str accessor applies string methods to every value: strip, lower, title, replace, contains, split and many more.