1. chapter1
import pandas as pddog_data = [['Bella', 'Labrador', 'Brown', 56, 24, '2013-07-01'],['Charlie', 'Poodle', 'Black', 43, 24, '2016-09-16'],['Lucy', 'Chow Chow', 'Brown', 46, 24, '2014-08-25'],['Cooper', 'Schnauzer', 'Gray', 49, 17, '2011-12-11'],['Max', 'Labrador', 'Black', 59, 29, '2017-01-20'],['Stella', 'Chihuahua', 'Tan', 18, 2, '2015-04-20'],['Bernie', 'St. Bernard', 'White', 77, 74, '2018-02-27']]dogs = pd.DataFrame(dog_data,columns = ["name","breed","color","height_cm","weight_kg","date_of_birth"])dogs
1.1 Exploring a DataFrame:
- .head() returns the first few rows
- .info() shows information on each of the columns, the data type and number of missing values
- .shape returns the number of rows and columns
.describe() calculates a few summary statistics for each column
1.2 Components of a DataFrame:
.values A two-dimensional NumPy array of values.
- .columns An index of columns: the column names
.index An index for the rows: either row numbers or row names
2.1 Sorting
.sort_values()
dogs.sort_values("weight_kg") dogs.sort_values("weight_kg", ascending=False) dogs.sort_values(["weight_kg", "height_cm"]) dogs.sort_values(["weight_kg", "height_cm"], ascending=[True, False])2.2 Subsetting
2.2.1 Subsetting columns

dogs["name"] dogs[["breed", "height_cm"]]2.2.2 Subsetting rows
dogs[dogs["height_cm"] > 50] dogs[dogs["breed"] == "Labrador"] dogs[(dogs["breed"] == "Labrador") & (dogs["color"] == "Brown")]2.2.3 using .isin()
is_black_or_brown = dogs["color"].isin(["Black", "Brown"]) dogs[is_black_or_brown]2.3 Adding a new column
dogs["height_m"] = dogs["height_cm"] / 100 print(dogs) dogs["bmi"] = dogs["weight_kg"] / dogs["height_m"] ** 2
2. chapter2
4_chapter2.pdf
分组聚合:按行分组,按列聚合
1.1 Summarizing numerical data
.median() , .mode()
.min() , .max()
.var() , .std()
.sum()
.quantile()
1.2 .agg()方法: apply functions to more than one column of a DataFrame
def pct30(column):
return column.quantile(0.3)
def pct40(column):
return column.quantile(0.4)
dogs["weight_kg"].agg(pct30)
dogs[["weight_kg", "height_cm"]].agg(pct30)
dogs["weight_kg"].agg([pct30, pct40])
1.3 Cumulative statistics
.cummax()
.cummin()
.cumsum()
.cumprod()
1.4 Counting
# Dropping duplicate names:
unique_dogs = vet_visits.drop_duplicates(subset=["name", "breed"])
unique_dogs["breed"].value_counts()
unique_dogs["breed"].value_counts(sort=True)
# 展示计数比例
unique_dogs["breed"].value_counts(normalize=True)
1.5 Grouped summary statistics
dogs.groupby("color")["weight_kg"].mean()
# Multiple grouped summaries
dogs.groupby("color")["weight_kg"].agg([min, max, sum])
# Grouping by multiple variables
dogs.groupby(["color", "breed"])["weight_kg"].mean()
# Many groups, many summaries
dogs.groupby(["color", "breed"])[["weight_kg", "height_cm"]].mean()
1.6 pivot_table

dogs.groupby("color")["weight_kg"].mean()
dogs.pivot_table(values="weight_kg", index="color")
dogs.pivot_table(values="weight_kg", index="color", aggfunc=[np.mean, np.median])
dogs.groupby(["color", "breed"])["weight_kg"].mean()
dogs.pivot_table(values="weight_kg", index="color", columns="breed")
dogs.pivot_table(values="weight_kg", index="color", columns="breed", fill_value=0)
3. chapter3
1.1 Setting a column as the index:.set_index()
dogs_ind = dogs.set_index("name")
1.2 Removing an index
dogs_ind.reset_index()
dogs_ind.reset_index(drop=True)
1.3 Indexes make subsetting simpler
dogs[dogs["name"].isin(["Bella", "Stella"])]
dogs_ind.loc[["Bella", "Stella"]]
1.4 Multi-level indexes / hierarchical indexes
dogs_ind3 = dogs.set_index(["breed", "color"])
# Subset the outer level with a list
dogs_ind3.loc[["Labrador", "Chihuahua"]]
# Subset inner levels with a list of tuples
dogs_ind3.loc[[("Labrador", "Brown"), ("Chihuahua", "Tan")]]
1.5 sort_index()
dogs_ind3.sort_index()
dogs_ind3.sort_index(level=["color", "breed"], ascending=[True, False])
2.1 slicing and subsetting(切片之前需要sort_index(),否则报错)

dogs_srt = dogs.set_index(["breed", "color"]).sort_index()
#1. Slicing the outer index level
dogs_srt.loc["Chow Chow":"Poodle"]
#2. Slicing the inner index levels
dogs_srt.loc[("Labrador", "Brown"):("Schnauzer", "Grey")]
#3. Slicing columns
dogs_srt.loc[:, "name":"height_cm"]
#4. Slice twice
dogs_srt.loc[ ("Labrador", "Brown"):("Schnauzer", "Grey"), "name":"height_cm"]
# slicing dates
dogs = dogs.set_index("date_of_birth").sort_index()
dogs.loc["2014-08-25":"2016-09-16"]
dogs.loc["2014":"2016"]
2.2 pivot_table
A pivot table is just a DataFrame with sorted indexes: 可以使用切片
dogs_height_by_breed_vs_color = dog_pack.pivot_table( "height_cm", index="breed", columns="color")
dogs_height_by_breed_vs_color.loc["Chow Chow":"Poodle"]
# The axis argument
dogs_height_by_breed_vs_color.mean(axis="index")
dogs_height_by_breed_vs_color.mean(axis="columns")
4. chapter4
1.1 Visualizing your data: pandas绘图
#1. 直方图
dog_pack["height_cm"].hist()
dog_pack["height_cm"].hist(bins=5)
#2. 条形图
avg_weight_by_breed = dog_pack.groupby("breed")["weight_kg"].mean()
avg_weight_by_breed.plot(kind="bar", title="Mean Weight by Dog Breed")
#3. 线图
sully.plot(x="date", y="weight_kg", kind="line")
#4. 散点图
dog_pack.plot(x="height_cm", y="weight_kg", kind="scatter")
1.2 Missing values
- Detecting missing values: .isna()
- Detecting missing values: .isna().any()
- Counting missing values: .isna().sum()
- Removing missing values: .dropna()
Replacing missing values: .fillna()
# Plotting missing values import matplotlib.pyplot as plt dogs.isna().sum().plot(kind="bar") plt.show()1.3 Creating DataFrames

From a list of dictionaries: Constructed row by row
import pandas as pd list_of_dicts = [ {"name": "Ginger", "breed": "Dachshund", "height_cm": 22, "weight_kg": 10, "date_of_birth": "2019-03-14"}, {"name": "Scout", "breed": "Dalmatian", "height_cm": 59, "weight_kg": 25, "date_of_birth": "2019-05-09"} ] new_dogs = pd.DataFrame(list_of_dicts) new_dogsFrom a dictionary of lists: Constructed column by column
dict_of_lists = { "name": ["Ginger", "Scout"], "breed": ["Dachshund", "Dalmatian"], "height_cm": [22, 59], "weight_kg": [10, 25], "date_of_birth": ["2019-03-14", "2019-05-09"] } new_dogs = pd.DataFrame(dict_of_lists) new_dogs1.4 Reading and writing CSVs
CSV to DataFrame: pd.read_csv()
import pandas as pd new_dogs = pd.read_csv("new_dogs.csv")DataFrame to CSV: pd.to_csv()
new_dogs.to_csv("new_dogs_with_bmi.csv")
