Pandas: Data Processing and Analysis with Python

1. Series and DataFrame

The two core data structures of Pandas:

  • Series: One-dimensional, indexed data structure.
  • DataFrame: Two-dimensional, tabular data structure with row indexes and column names.
import pandas as pd
import numpy as np

s = pd.Series([10, 20, 30], name="score")

df = pd.DataFrame({
    "name": ["Alice", "Bob", "Charlie", "David"],
    "age": [25, 30, 28, 35],
    "city": ["Tokyo", "Osaka", "Tokyo", "Kyoto"],
    "salary": [5000, 7000, 6000, 9000],
})

Basic properties

df.shape           # (4, 4)
df.columns         # List
df.index           # row index
df.dtypes          # Data type of each column
df.size            # total number of elements
df.empty           # Is it empty

Data check

df.head()          # first 5 lines
df.tail()          # Next 5 lines
df.sample(2)       # random sampling

df.info()          # Type, non-empty quantity, memory, etc.
df.describe()      # Descriptive statistics
df.describe(include="all")

DataFrame does not require that all columns use the same dtype, which is an important difference from NumPy ndarray.

2. Data reading and saving

CSV

df = pd.read_csv("data.csv")

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

Commonly used parameters:

df = pd.read_csv(
    "data.csv",
    usecols=["name", "age", "salary"],
    dtype={"age": "Int64"},
    parse_dates=["created_at"] if False else None,
    encoding="utf-8",
)

Commonly used parameters include:

  • usecols: Only read the specified columns.
  • dtype: Specifies the data type.
  • parse_dates: Parse date column.
  • encoding: Specifies text encoding.
  • chunksize: Read large files in chunks.

Date columns can usually be specified directly:

df = pd.read_csv(
    "data.csv",
    parse_dates=["created_at"],
)

Excel、JSON、Parquet

pd.read_excel("data.xlsx")
pd.read_json("data.json")
pd.read_parquet("data.parquet")

df.to_excel("output.xlsx", index=False)
df.to_json("output.json", orient="records")
df.to_parquet("output.parquet", index=False)

Parquet is a columnar storage format that is generally more suitable for repeated reading, type preservation, and efficient storage of analytical data.

SQL

from sqlalchemy import create_engine

engine = create_engine("postgresql+psycopg://user:password@localhost/db")

df = pd.read_sql(
    "SELECT name, age, salary FROM employees",
    engine,
)

In actual development, database credentials should be managed through environment variables or Secrets Manager and should not be hard-coded.

3. Selecting / Indexing: Select data

This is the most commonly used set of operations for Pandas.

select column

df["salary"]                  # Series
df[["name", "salary"]]        # DataFrame

loc: based on tags

df.loc[0, "name"]
df.loc[0:2, ["name", "salary"]]

loc uses row and column labels, and label slices usually include end labels.

iloc: based on location

df.iloc[0, 1]
df.iloc[0:2, 1:3]

iloc uses integer positions and the slicing behavior is similar to Python, the end position is not included.

Boolean Filtering

df[df["salary"] > 6000]

df[
    (df["age"] >= 28) &
    (df["city"] == "Tokyo")
]

Commonly used conditional methods:

df[df["city"].isin(["Tokyo", "Osaka"])]

df[df["age"].between(25, 30)]

df[df["name"].str.contains("a", case=False, na=False)]

query()

For complex conditions, query() is sometimes more readable:

df.query("age >= 28 and salary > 6000")

The expression query() should not be directly concatenated with unvalidated user input.

Modify data

It is recommended to use loc directly:

df.loc[df["salary"] < 6000, "salary"] = 6000

Avoid chain assignments:

# Not recommended
df[df["salary"] < 6000]["salary"] = 6000

Pandas 3.0 has fully adopted Copy-on-Write, chained assignments cannot be used to update the original DataFrame.

4. Index and Index Alignment

An important feature of Pandas is that many operations of are aligned by index labels instead of simply calculated by position.

a = pd.Series([10, 20], index=["x", "y"])
b = pd.Series([1, 2], index=["y", "x"])

a + b

Result:

x    12
y    21

Because:

a["x"] + b["x"] = 10 + 2
a["y"] + b["y"] = 20 + 1

The default alignment may produce missing values if the labels do not match.

a.add(b, fill_value=0)

set_index / reset_index

df = df.set_index("name")

df = df.reset_index()

MultiIndex

Pandas also supports multi-level indexing:

df.set_index(["city", "name"])

Suitable for hierarchical data and multidimensional aggregations, but don't rely too much on MultiIndex for daily use; ordinary columns are usually more intuitive.

5. Missing Data: Missing value processing

Pandas Common missing value representations include:

  • NaN: Traditional floating point missing values.
  • NaT: Missing value for date and time.
  • pd.NA: Missing value used by part Nullable Dtype.

Detect missing values

df.isna()
df.isna().sum()
df.notna()

Remove missing values

df.dropna()

df.dropna(subset=["salary"])

Fill missing values

df["salary"] = df["salary"].fillna(0)

df["salary"] = df["salary"].fillna(
    df["salary"].median()
)

Forward and backward padding:

df["salary"] = df["salary"].ffill()
df["salary"] = df["salary"].bfill()

These operations are especially common with time series data.

Note: Missing values of should not necessarily be filled with zeros. The decision to delete, populate, or retain should be based on business implications.

6. Data Cleaning: Data cleaning

Modify data type

df["age"] = df["age"].astype("Int64")
df["salary"] = df["salary"].astype("float64")

Int64 here is Pandas Nullable Integer Dtype, which can represent missing integers.

safe conversion

df["salary"] = pd.to_numeric(
    df["salary"],
    errors="coerce",
)

Unresolvable values are converted to missing values.

df["created_at"] = pd.to_datetime(
    df["created_at"],
    errors="coerce",
    utc=True,
)

Duplicate values

df.duplicated()
df.duplicated(subset=["name"])

df = df.drop_duplicates(
    subset=["name"],
    keep="first",
)

Modify column name

df = df.rename(columns={
    "salary": "monthly_salary"
})

replace

df["city"] = df["city"].replace({
    "Tokio": "Tokyo",
    "Oska": "Osaka",
})

String processing

Pandas Use .str to access string operations:

df["name"].str.lower()
df["name"].str.strip()
df["name"].str.len()
df["name"].str.contains("a", na=False)
df["name"].str.replace(" ", "_", regex=False)
df["name"].str.split(" ")

These operations are commonly used for text field cleaning, feature construction, and data standardization.

7. GroupBy: Group aggregation

GroupBy is one of the most important functions of Pandas.

Basic model:

Split → Apply → Combine

DataFrame
    ↓
Split into Groups
    ↓
Aggregate / Transform / Filter
    ↓
Combine Results

Basic aggregation

df.groupby("city")["salary"].mean()

Multi-column aggregation:

df.groupby("city").agg(
    avg_salary=("salary", "mean"),
    max_salary=("salary", "max"),
    employee_count=("name", "count"),
)

multi-level grouping

df.groupby(["city", "age"])["salary"].mean()

as_index=False

By default, the grouping key usually becomes the result index.

df.groupby("city", as_index=False)["salary"].mean()

The normal column structure can be preserved.

The difference between agg, transform and filter

methodFeatures
agg()Each group produces aggregated results
transform()Return results that can be aligned with the original data
filter()Keep or delete entire groups based on group-level conditions
apply()Custom complex logic, usually slower

transform()

For example, calculate the difference between each person's salary and the average salary in the city:

city_avg = df.groupby("city")["salary"].transform("mean")

df["salary_diff"] = df["salary"] - city_avg

transform() is very suitable for scenarios such as intra-group standardization and intra-group ranking.

filter()

For example, only keep cities with at least two employees:

df.groupby("city").filter(
    lambda group: len(group) >= 2
)

If the built-in aggregate function can meet the requirements, agg() and transform() should usually be used in preference to custom apply().

8. Merge, Join and Concat

Pandas provides similar data correlation functionality to SQL Join.

Assumptions:

employees = pd.DataFrame({
    "employee_id": [1, 2, 3],
    "department_id": [10, 20, 10],
})

departments = pd.DataFrame({
    "department_id": [10, 20],
    "department_name": ["Engineering", "Sales"],
})

merge()

result = employees.merge(
    departments,
    on="department_id",
    how="left",
)

Main connection types:

howmeaning
innerOnly keep matching data on both sides
leftKeep all data in the left table
rightKeep all data in the right table
outerKeep all Key on both sides
crossCartesian product

validate

Used to verify the relationship Join Key:

employees.merge(
    departments,
    on="department_id",
    how="left",
    validate="many_to_one",
)

This parameter is very practical and can avoid unexpected expansion of the number of rows due to repeated Key.

indicator

Check which side the data comes from:

employees.merge(
    departments,
    on="department_id",
    how="outer",
    indicator=True,
)

The result will be the addition of _merge columns.

concat()

Splice along rows or columns:

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

combined_cols = pd.concat([df1, df2], axis=1)

concat() is not responsible for SQL style key connections.

Also note: merge() may match Join Key where both sides are missing, which is different from the usual semantics of SQL where NULL = NULL does not hold.

9. Pivot, Melt and Crosstab

Used to change the organizational form of data.

pivot()

Convert from long table to wide table:

df.pivot(
    index="date",
    columns="product",
    values="sales",
)

Each index + columns combination is required to uniquely determine a value.

pivot_table()

Allows aggregation of repeated combinations:

df.pivot_table(
    index="city",
    columns="department",
    values="salary",
    aggfunc="mean",
)

melt()

Convert a wide table to a long table:

pd.melt(
    df,
    id_vars=["name"],
    value_vars=["sales_2024", "sales_2025"],
    var_name="year",
    value_name="sales",
)

crosstab()

Used to count frequencies between categorical variables:

pd.crosstab(df["city"], df["department"])

pivot_table() and melt() are frequently used in analysis reports and feature engineering.

10. Sorting, Ranking and statistics

sort

df.sort_values("salary", ascending=False)

df.sort_values(
    ["city", "salary"],
    ascending=[True, False],
)

Ranking

df["salary_rank"] = df["salary"].rank(
    ascending=False
)

Ranking within the group:

df["city_rank"] = (
    df.groupby("city")["salary"]
    .rank(ascending=False)
)

Commonly used statistics

df["salary"].mean()
df["salary"].median()
df["salary"].std()
df["salary"].quantile(0.9)

df["city"].value_counts()
df["city"].nunique()
df["city"].unique()

Correlation coefficient

df[["age", "salary"]].corr()

Accumulation and difference

df["salary"].cumsum()
df["salary"].cummax()
df["salary"].diff()
df["salary"].pct_change()

These functions are commonly used for growth rates, changes, trend analysis, and feature engineering.

Note that pct_change() returns a proportional change, for example 0.1 represents a 10% increase.

11. Window Functions: Window calculation

Pandas provides data analysis capabilities similar to SQL Window Function.

shift()

Move data forward or backward:

df["prev_salary"] = df["salary"].shift(1)

rolling()

Rolling window:

df["rolling_mean"] = (
    df["salary"]
    .rolling(window=3)
    .mean()
)

expanding()

Continuously expanding the window from the starting point of the sequence:

df["expanding_mean"] = (
    df["salary"]
    .expanding()
    .mean()
)

ewm()

Exponentially weighted window:

df["ewm_mean"] = (
    df["salary"]
    .ewm(span=3, adjust=False)
    .mean()
)
methodmeaning
shift()Lag/Lead
rolling()fixed scrolling window
expanding()Cumulative expansion window
ewm()exponential weighted window

In real time series calculations, you should first sort by time, and if necessary, group by entities such as users and products, otherwise rolling calculations may mix different entities or order them in the wrong order.

12. Time Series: Time series processing

Pandas provides relatively complete support for time series.

Datetime

df["date"] = pd.to_datetime(df["date"])

df["year"] = df["date"].dt.year
df["month"] = df["date"].dt.month
df["day"] = df["date"].dt.day
df["weekday"] = df["date"].dt.dayofweek

time filter

df[df["date"] >= "2026-01-01"]

Resampling

Used to aggregate by fixed time frequency.

daily = df.set_index("date")

monthly = daily["sales"].resample("MS").sum()

MS represents the frequency at the beginning of the month; ME represents the frequency at the end of the month.

time zone

df["date"] = pd.to_datetime(df["date"], utc=True)

df["date"] = df["date"].dt.tz_convert("Asia/Tokyo")
  • tz_localize(): Specifies a time zone for times without a time zone.
  • tz_convert(): Convert a time zone that already has time zone awareness.

These are two different operations.

13. Apply, Map and vectorization

map()

Suitable for Series element mapping:

df["city_code"] = df["city"].map({
    "Tokyo": "TK",
    "Osaka": "OS",
    "Kyoto": "KY",
})

apply()

Suitable for executing custom functions along rows or columns:

df["salary_level"] = df["salary"].apply(
    lambda x: "high" if x >= 7000 else "low"
)

But for simple calculations, vectorization is preferred:

df["salary_after_tax"] = df["salary"] * 0.8

df["salary_level"] = np.where(
    df["salary"] >= 7000,
    "high",
    "low",
)

Performance and readability are usually better.

apply() is not equal to vectorization. and especially axis=1's row-by-row custom Python functions can be significantly slower on large data sets.

14. Data Type and Category

Pandas supports multiple data types:

TypePurpose
int64 / float64numerical value
Int64 / Float64Supports the nullable numeric type pd.NA
str / stringtext
booleannullable boolean type
categoryLow cardinality string or categorical variable
datetime64date time
timedelta64time difference

Category

For example, for a million rows of data, city only contains a few different values:

df["city"] = df["city"].astype("category")

category Reduces duplicate text storage through category encoding, which often saves memory on low-cardinality categorical columns.

However, if most of the values do not repeat, it may not be suitable to use category.

Pandas 3.0 The default string type has changed, and you can no longer assume that string columns must use NumPy object dtype.

15. Copy-on-Write(CoW)

This is an important behavioral characteristic of Pandas 3.x.

Main goals of Copy-on-Write:

  • Avoid ambiguous data sharing modifications.
  • Delay data replication when possible.
  • Make indexing and assignment behavior more predictable.

For example:

df = pd.DataFrame({"score": [10, 20, 30]})

subset = df["score"]

subset.iloc[0] = 100

In Pandas 3.x, modifying subset does not also modify the original df.

If you need to modify df:

df.loc[0, "score"] = 100

Also avoid:

# Not recommended
df["score"][0] = 100

Should be changed to:

df.loc[0, "score"] = 100

Copy-on-Write does not mean that all operations do not copy data, but it makes the behavior of data sharing and modification clearer.

16. Performance and memory optimization

View memory

df.memory_usage(deep=True)

Reduce unnecessary columns

df = pd.read_csv(
    "large.csv",
    usecols=["user_id", "date", "amount"],
)

Use appropriate dtype

df["user_id"] = df["user_id"].astype("int32")

df["city"] = df["city"].astype("category")

Before narrowing down the numeric type, confirm the numeric range and precision requirements.

Read in chunks

for chunk in pd.read_csv("large.csv", chunksize=100_000):
    result = chunk.groupby("city")["sales"].sum()

If you want to count the entire file, you should continue to merge the aggregate results of each Chunk instead of directly treating the statistical value of a single Chunk as the global result.

Avoid circular splicing

Not recommended:

df = pd.DataFrame()

for item in items:
    df = pd.concat([df, pd.DataFrame([item])])

It is recommended to collect the results first:

records = []

for item in items:
    records.append(item)

df = pd.DataFrame(records)

When to consider other tools?

  • NumPy: A large number of purely numerical array and matrix operations.
  • Pandas: Small and medium-scale structured tabular data analysis.
  • Polars: Want to take advantage of multi-threading and columnar execution for data processing.
  • DuckDB: Use SQL to analyze CSV, Parquet and other data.
  • Spark: Distributed large-scale data processing is required.

Large amounts of data do not automatically mean that tools must be changed. Memory, computational bottlenecks, and usage scenarios should be checked first.


Summary

Knowledge pointsimportance
Series / DataFramecore
read_csv / read_parquethigh frequency
loc / iloc / Boolean Filteringcore
Index AlignmentImportant features
Missing Data / Data Cleaningcore
GroupBy / agg / transformcore
merge / join / concatcore
pivot_table / melthigh frequency
Sorting / Ranking / Statisticshigh frequency
shift / rolling / expandingCommonly used
Datetime / ResamplingTime series essential
map / apply / Vectorizationimportant
dtype / categoryimportant
Copy-on-WriteImportant features
Chunk Processing / Memory Optimizationon demand

Pandas The five most important knowledge points:

  1. DataFrame / Series: Tag-based data structure that supports different columns using different types.
  2. Index Alignment: Operations are often aligned by index label rather than position.
  3. GroupBy: Implement group aggregation, group conversion and intra-group calculation.
  4. Merge / Pivot: Realize the association and table structure conversion of different data sources.
  5. Copy-on-Write: Controls data sharing and modification behavior between objects.

Typical processing flow of actual data analysis:

CSV / Excel / SQL / Parquet
            ↓
         Read Data
            ↓
     Inspect / Validate
            ↓
    Clean / Transform
            ↓
      Merge / Join
            ↓
   GroupBy / Aggregation
            ↓
 Statistics / Feature Engineering
            ↓
   Export / Visualization

Reference documentation

Back to top