专业的编程技术博客社区

网站首页 > 博客文章 正文

《pandas库(数据处理)》

baijin 2025-08-05 17:24:02 博客文章 1 ℃ 0 评论

一、pandas基础

1. 安装与导入

pip install pandas
import pandas as pd

2. 核心数据结构

  • Series:一维数组,类似带标签的列表。
  • DataFrame:二维表格,类似Excel或SQL表。
# 创建Series
s = pd.Series([1, 3, 5, np.nan, 6], index=['a', 'b', 'c', 'd', 'e'])
print(s)
# 输出:
# a    1.0
# b    3.0
# c    5.0
# d    NaN
# e    6.0
# dtype: float64

# 创建DataFrame
data = {'Name': ['Tom', 'Nick', 'John'],
        'Age': [28, 32, 25],
        'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)
print(df)
# 输出:
#    Name  Age      City
# 0   Tom   28  New York
# 1  Nick   32  London
# 2  John   25   Paris

二、数据读写

1. 读取文件

# CSV文件
df = pd.read_csv("data.csv")

# Excel文件
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")

# JSON文件
df = pd.read_json("data.json")

# SQL数据库
import sqlite3
conn = sqlite3.connect("database.db")
df = pd.read_sql_query("SELECT * FROM table", conn)

2. 写入文件

df.to_csv("output.csv", index=False)  # 不保存索引
df.to_excel("output.xlsx", sheet_name="Results")

三、数据清洗

1. 查看数据概览

print(df.head())          # 查看前5行
print(df.tail())          # 查看后5行
print(df.info())          # 查看数据类型和缺失值
print(df.describe())      # 统计摘要(均值、标准差等)

2. 处理缺失值

# 删除含缺失值的行
df.dropna(inplace=True)

# 填充缺失值
df.fillna(0, inplace=True)  # 用0填充
df["Age"].fillna(df["Age"].mean(), inplace=True)  # 用均值填充

3. 数据类型转换

# 转换列类型
df["Age"] = df["Age"].astype(int)

# 处理日期
df["Date"] = pd.to_datetime(df["Date"], format="%Y-%m-%d")

4. 重命名列与索引

# 重命名列
df.rename(columns={"OldName": "NewName"}, inplace=True)

# 重置索引
df.reset_index(drop=True, inplace=True)

四、数据操作

1. 筛选与过滤

# 按条件筛选
df_filtered = df[df["Age"] > 30]

# 多条件筛选
df_filtered = df[(df["Age"] > 30) & (df["City"] == "New York")]

2. 排序与排名

# 按列排序
df_sorted = df.sort_values(by="Age", ascending=False)

# 按值排名
df["Rank"] = df["Score"].rank(method="dense", ascending=False)

3. 分组聚合

# 按City分组,计算平均年龄
grouped = df.groupby("City")["Age"].mean()
print(grouped)
# 输出:
# City
# London      32.0
# New York    28.0
# Paris       25.0
# Name: Age, dtype: float64

# 多指标聚合
agg_result = df.groupby("City").agg({"Age": "mean", "Score": "sum"})

4. 合并与连接

# 合并两个DataFrame
df1 = pd.DataFrame({"Key": ["K0", "K1"], "A": ["A0", "A1"]})
df2 = pd.DataFrame({"Key": ["K0", "K1"], "B": ["B0", "B1"]})
merged_df = pd.merge(df1, df2, on="Key")
print(merged_df)
# 输出:
#   Key   A   B
# 0  K0  A0  B0
# 1  K1  A1  B1

五、数据可视化

import matplotlib.pyplot as plt

# 柱状图
df["Sales"].plot(kind="bar")
plt.title("Sales by Region")
plt.show()

# 散点图
df.plot.scatter(x="Age", y="Income")
plt.show()

# 直方图
df["Score"].plot.hist(bins=10)
plt.show()

六、实战案例:电商数据分析

需求:分析用户购买行为,找出高价值客户。

# 1. 读取数据
orders = pd.read_csv("orders.csv")

# 2. 数据清洗
orders["OrderDate"] = pd.to_datetime(orders["OrderDate"])
orders.dropna(subset=["UserId", "Amount"], inplace=True)

# 3. 关键指标计算
orders["YearMonth"] = orders["OrderDate"].dt.to_period("M")
monthly_sales = orders.groupby("YearMonth")["Amount"].sum()
print(monthly_sales)

# 4. 高价值客户筛选
top_customers = orders.groupby("UserId")["Amount"].sum().nlargest(10)
print(top_customers)

七、常见问题与解决方案

1.SettingWithCopyWarning警告

现象:修改DataFrame子集时触发警告。
解决:使用.loc明确索引:

df.loc[df["Age"] > 30, "Category"] = "Senior"

2. 处理大数据集内存不足

解决:使用chunksize分块读取:

chunk_iter = pd.read_csv("large_data.csv", chunksize=10000)
for chunk in chunk_iter:
    process(chunk)  # 逐块处理

3. 合并时索引不匹配

解决:重置索引或明确合并键:

df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
merged_df = pd.concat([df1, df2], axis=1)

八、总结与下一步

  • 核心收获
    • 掌握DataFrame/Series操作、数据读写、清洗、聚合与可视化。
    • 能解决实际问题(如用户行为分析、销售报表生成)。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表