Skip to content

Pandas 基础

社科数据分析的核心工具 —— Python 版的 Stata


什么是 Pandas?

Pandas = Python Data Analysis Library

为什么社科学生必学 Pandas?

  • 处理表格数据(类似 Excel/Stata)
  • 数据清洗、筛选、合并
  • 分组统计、透视表
  • 时间序列分析

核心数据结构

1. Series(一维)

python
import pandas as pd

# 类似一列数据
ages = pd.Series([25, 30, 35, 40], name='age')
print(ages)

2. DataFrame(二维表格)

python
# 类似 Stata dataset 或 Excel 表格
df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Carol'],
    'age': [25, 30, 35],
    'income': [50000, 75000, 85000]
})
print(df)

创建 DataFrame

python
import pandas as pd

# 方法 1:从字典
df = pd.DataFrame({
    'respondent_id': [1001, 1002, 1003],
    'age': [25, 30, 35],
    'gender': ['M', 'F', 'M'],
    'income': [50000, 75000, 85000]
})

# 方法 2:从列表
data = [
    [1001, 25, 'M', 50000],
    [1002, 30, 'F', 75000],
    [1003, 35, 'M', 85000]
]
df = pd.DataFrame(data, columns=['id', 'age', 'gender', 'income'])

# 方法 3:从 CSV
df = pd.read_csv('survey.csv')

# 方法 4:从 Stata
df = pd.read_stata('survey.dta')

查看数据

python
df.head()       # 前5行
df.tail(10)     # 后10行
df.shape        # (行数, 列数)
df.columns      # 列名
df.dtypes       # 数据类型
df.info()       # 数据概览
df.describe()   # 描述性统计

选择数据

选择列

python
# 单列(返回 Series)
ages = df['age']

# 多列(返回 DataFrame)
subset = df[['name', 'age', 'income']]

选择行

python
# 按位置(iloc)
df.iloc[0]       # 第1行
df.iloc[0:3]     # 前3行
df.iloc[[0, 2]]  # 第1和第3行

# 按标签(loc)
df.loc[0]        # 索引为0的行
df.loc[0:2]      # 索引0到2的行

条件筛选

python
# 单条件
df[df['age'] > 30]
df[df['gender'] == 'F']

# 多条件
df[(df['age'] > 25) & (df['income'] > 60000)]
df[(df['gender'] == 'M') | (df['age'] < 30)]

# query 方法(更简洁)
df.query('age > 30 and income > 60000')

️ 修改数据

新增列

python
# 基于已有列
df['log_income'] = np.log(df['income'])
df['age_squared'] = df['age'] ** 2

# 条件赋值
df['age_group'] = df['age'].apply(lambda x: '年轻' if x < 30 else '中年')

# 使用 np.where
df['high_income'] = np.where(df['income'] > 70000, 'Yes', 'No')

修改值

python
# 修改整列
df['income'] = df['income'] * 1.1  # 收入增加10%

# 条件修改
df.loc[df['age'] > 30, 'age_group'] = 'Senior'

删除

python
# 删除列
df.drop('age_squared', axis=1, inplace=True)
# 或
df = df.drop(columns=['age_squared'])

# 删除行
df.drop([0, 2], axis=0, inplace=True)

Stata 操作的 Pandas 对照

读取数据

stata
* Stata
use "survey.dta", clear
python
# Pandas
df = pd.read_stata('survey.dta')

查看数据

stata
* Stata
browse
describe
summarize
python
# Pandas
df.head()
df.info()
df.describe()

筛选

stata
* Stata
keep if age > 30
keep if gender == "M" & income > 60000
python
# Pandas
df = df[df['age'] > 30]
df = df[(df['gender'] == 'M') & (df['income'] > 60000)]

生成新变量

stata
* Stata
gen log_income = log(income)
gen high_earner = (income > 70000)
python
# Pandas
df['log_income'] = np.log(df['income'])
df['high_earner'] = df['income'] > 70000

排序

stata
* Stata
sort age
gsort -income  // 降序
python
# Pandas
df = df.sort_values('age')
df = df.sort_values('income', ascending=False)

实战案例

案例:完整的数据清洗流程

python
import pandas as pd
import numpy as np

# 1. 读取数据
df = pd.read_csv('raw_survey.csv')
print(f"原始数据: {len(df)} 行")

# 2. 删除缺失值
df = df.dropna(subset=['age', 'income'])

# 3. 筛选有效数据
df = df[
    (df['age'] >= 18) &
    (df['age'] <= 100) &
    (df['income'] > 0) &
    (df['income'] < 1000000)
]

# 4. 创建新变量
df['log_income'] = np.log(df['income'])
df['age_squared'] = df['age'] ** 2

# 5. 分类变量
df['age_group'] = pd.cut(
    df['age'],
    bins=[0, 30, 50, 100],
    labels=['青年', '中年', '老年']
)

df['income_quartile'] = pd.qcut(
    df['income'],
    q=4,
    labels=['Q1', 'Q2', 'Q3', 'Q4']
)

# 6. 描述性统计
print("\n=== 描述性统计 ===")
print(df.groupby('age_group')['income'].agg(['count', 'mean', 'std']))

# 7. 保存
df.to_csv('clean_survey.csv', index=False)
print(f"\n清洗后: {len(df)} 行")

常用技巧

链式操作

python
result = (df
    .query('age > 25')
    .assign(log_income=lambda x: np.log(x['income']))
    .sort_values('income', ascending=False)
    .head(10)
)

批量处理列

python
# 对多列应用同一函数
numeric_cols = ['age', 'income', 'education_years']
df[numeric_cols] = df[numeric_cols].apply(lambda x: x / x.max())  # 归一化

练习题

python
# 数据
df = pd.DataFrame({
    'id': range(1, 11),
    'age': [22, 35, 28, 45, 30, 50, 25, 38, 42, 29],
    'income': [45000, 75000, 55000, 90000, 60000, 95000, 50000, 80000, 85000, 58000],
    'gender': ['M', 'F', 'M', 'F', 'M', 'M', 'F', 'F', 'M', 'F']
})

# 任务:
# 1. 筛选年龄30-45岁
# 2. 创建收入分组(<60k, 60-80k, >80k)
# 3. 按性别和收入分组统计平均年龄
# 4. 保存结果

下一步

下一节学习 Pandas 高级操作(合并、重塑、分组)。

继续!

基于 MIT 许可证发布。内容版权归作者所有。