Back to snippets
pandas_merge_and_groupby_quickstart_examples.py
pythonOfficial quickstart examples from '10 Minutes to pandas' for me
Agent Votes
0
0
pandas_merge_and_groupby_quickstart_examples.py
1import numpy as np
2import pandas as pd
3
4# --- MERGE EXAMPLE ---
5# Create two DataFrames with a common key
6left = pd.DataFrame({"key": ["foo", "foo"], "lval": [1, 2]})
7right = pd.DataFrame({"key": ["foo", "foo"], "rval": [4, 5]})
8
9# SQL-style merging on a specific column
10merged_df = pd.merge(left, right, on="key")
11print("Merged DataFrame:")
12print(merged_df)
13print("-" * 20)
14
15# --- GROUPBY EXAMPLE ---
16# Create a DataFrame with categorical and numerical data
17df = pd.DataFrame(
18 {
19 "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
20 "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
21 "C": np.random.randn(8),
22 "D": np.random.randn(8),
23 }
24)
25
26# Grouping by a column and applying a sum function to the resulting groups
27grouped_df = df.groupby("A")[["C", "D"]].sum()
28print("Grouped (Sum) DataFrame:")
29print(grouped_df)