pandas and NumPy 3 cheatsheet

pandas and NumPy 3: Grouping and combining

7 common pandas and NumPy 3 tasks.

Group and aggregate

Compute several statistics per group with named results.

df.groupby("country").agg(users=("id", "count"), avg_age=("age", "mean"))

Create a pivot table

Summarize values across two dimensions.

df.pivot_table(index="country", columns="plan", values="revenue", aggfunc="sum")

Join two DataFrames

Join on a key, like SQL. how can be inner, left, right or outer.

pd.merge(orders, users, left_on="user_id", right_on="id", how="left")

Stack DataFrames

Append DataFrames with the same columns.

pd.concat([df1, df2], ignore_index=True)

Compute a moving average

Average over a sliding window of seven rows.

df["avg_7"] = df["sales"].rolling(7).mean()

Aggregate by time period

Sum values by month. The index must be a datetime.

df.set_index("date")["sales"].resample("MS").sum()

Save to a CSV file

Write the DataFrame to a file without the row index.

df.to_csv("out.csv", index=False)

Was this page helpful?