数据分析:Pandas与数据清洗实战

数据分析:Pandas与数据清洗实战

大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊数据分析这个话题。作为一个全栈开发者,我经常需要处理各种数据。Pandas是Python中最流行的数据处理库,今天就来分享一下Pandas的使用技巧和数据清洗实战经验。

为什么选择Pandas?

Pandas是一个强大的数据处理和分析库,提供了:

  • 高效的数据结构(DataFrame和Series)
  • 强大的数据清洗能力
  • 灵活的数据操作
  • 丰富的统计功能

安装Pandas

bash 复制代码
pip install pandas
pip install numpy matplotlib seaborn

数据结构基础

Series

python 复制代码
import pandas as pd
import numpy as np

# 创建Series
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)

# 索引
s.index = ['a', 'b', 'c', 'd', 'e', 'f']

# 访问元素
print(s['a'])
print(s[0])

DataFrame

python 复制代码
# 创建DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 35, 40],
    'City': ['New York', 'London', 'Paris', 'Tokyo']
}
df = pd.DataFrame(data)
print(df)

# 查看数据
print(df.head())
print(df.tail())
print(df.info())
print(df.describe())

数据读取

python 复制代码
# 读取CSV
df = pd.read_csv('data.csv')

# 读取Excel
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

# 读取JSON
df = pd.read_json('data.json')

# 读取数据库
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql('SELECT * FROM table', conn)

数据清洗实战

处理缺失值

python 复制代码
# 查看缺失值
print(df.isnull().sum())

# 删除缺失值
df_clean = df.dropna()

# 填充缺失值
df['Age'].fillna(df['Age'].mean(), inplace=True)
df['City'].fillna('Unknown', inplace=True)

# 向前填充/向后填充
df.fillna(method='ffill', inplace=True)
df.fillna(method='bfill', inplace=True)

处理重复值

python 复制代码
# 查找重复值
print(df.duplicated())

# 删除重复值
df.drop_duplicates(inplace=True)

数据类型转换

python 复制代码
# 转换为字符串
df['Name'] = df['Name'].astype(str)

# 转换为日期
df['Date'] = pd.to_datetime(df['Date'])

# 转换为数值
df['Price'] = pd.to_numeric(df['Price'], errors='coerce')

数据过滤

python 复制代码
# 基本过滤
filtered = df[df['Age'] > 30]

# 多条件过滤
filtered = df[(df['Age'] > 30) & (df['City'] == 'London')]

# 使用query方法
filtered = df.query('Age > 30 and City == "London"')

数据转换

python 复制代码
# 使用apply
df['UpperName'] = df['Name'].apply(str.upper)

# 使用map
city_map = {'New York': 'NY', 'London': 'LDN'}
df['CityCode'] = df['City'].map(city_map)

# 使用replace
df['City'] = df['City'].replace({'New York': 'NYC'})

数据聚合

python 复制代码
# 分组统计
grouped = df.groupby('City')['Age'].mean()

# 多列聚合
grouped = df.groupby('City').agg({
    'Age': ['mean', 'max', 'min'],
    'Name': 'count'
})

# 透视表
pivot = df.pivot_table(values='Age', index='City', aggfunc='mean')

实战案例:电商数据分析

python 复制代码
# 加载数据
df = pd.read_csv('ecommerce_data.csv')

# 数据探索
print(df.shape)
print(df.columns)
print(df.dtypes)
print(df.isnull().sum())

# 数据清洗
df['order_date'] = pd.to_datetime(df['order_date'])
df['total_amount'] = pd.to_numeric(df['total_amount'], errors='coerce')
df['total_amount'].fillna(df['total_amount'].mean(), inplace=True)
df.drop_duplicates(inplace=True)

# 添加新特征
df['month'] = df['order_date'].dt.month
df['year'] = df['order_date'].dt.year
df['day_of_week'] = df['order_date'].dt.dayofweek

# 分析
monthly_sales = df.groupby('month')['total_amount'].sum()
category_sales = df.groupby('category')['total_amount'].sum()
customer_purchases = df.groupby('customer_id')['total_amount'].sum().sort_values(ascending=False)

# 可视化
import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(12, 6))
monthly_sales.plot(kind='bar')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Total Amount')
plt.show()

高级技巧

合并数据

python 复制代码
# 合并DataFrame
df1 = pd.DataFrame({'key': ['A', 'B', 'C'], 'value1': [1, 2, 3]})
df2 = pd.DataFrame({'key': ['B', 'C', 'D'], 'value2': [4, 5, 6]})

# 内连接
merged = pd.merge(df1, df2, on='key')

# 左连接
merged = pd.merge(df1, df2, on='key', how='left')

# 右连接
merged = pd.merge(df1, df2, on='key', how='right')

# 外连接
merged = pd.merge(df1, df2, on='key', how='outer')

时间序列分析

python 复制代码
# 创建时间序列
dates = pd.date_range('2023-01-01', periods=100, freq='D')
ts = pd.Series(np.random.randn(100), index=dates)

# 移动窗口
rolling = ts.rolling(window=7).mean()

# 差分
diff = ts.diff()

# 重采样
weekly = ts.resample('W').sum()

性能优化

python 复制代码
# 使用dtypes减少内存
df['Age'] = df['Age'].astype('int8')
df['Score'] = df['Score'].astype('float32')

# 使用query代替loc
result = df.query('Age > 30')

# 使用vectorized操作
df['Total'] = df['Price'] * df['Quantity']

# 使用Categorical类型
df['Category'] = df['Category'].astype('category')

数据导出

python 复制代码
# 导出CSV
df.to_csv('cleaned_data.csv', index=False)

# 导出Excel
df.to_excel('cleaned_data.xlsx', sheet_name='Data')

# 导出JSON
df.to_json('cleaned_data.json')

# 导出到数据库
conn = sqlite3.connect('database.db')
df.to_sql('cleaned_data', conn, if_exists='replace')

总结

Pandas是数据分析的利器,掌握它可以大大提高数据处理的效率。从数据读取到清洗,再到分析和可视化,Pandas都能胜任。

我的鬃狮蜥Hash对数据分析也有自己的理解------它总是根据蟋蟀的大小来决定捕食策略,这也许就是自然界的"数据驱动决策"吧!

如果你对数据分析感兴趣,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!


技术栈:Python · Pandas · NumPy · Matplotlib

相关推荐
Richown6 小时前
Web3钱包开发:使用Ethers.js集成MetaMask
区块链·react
Richown6 小时前
机器学习入门:TensorFlow.js实战
区块链·react
mutourend20 小时前
Zcash 与量子计算机
区块链·量子计算·后量子密码学
TechubNews1 天前
稳定币下一战:不是谁发币,而是谁掌握结算通道
人工智能·web3·区块链
mutourend1 天前
量子计算与区块链:让紧迫性与真实威胁相匹配
区块链·量子计算·后量子密码学
多年小白1 天前
A股算力租赁板块 深度分析
大数据·人工智能·ai·金融·区块链
架构源启1 天前
Spring AI 进阶系列- Agent 智能体开发:ReAct模式、多步推理与自主Agent实战
人工智能·spring·react·ai agent·智能体·springai
小牛itbull1 天前
ReactPress 3.0 :一分钟拥有自己的 CMS & 博客
开源·cms·react·博客系统·reactpress
黄焖鸡能干四碗2 天前
固定资产管理系统建设方案和源码(Java源码)
大数据·数据库·人工智能·物联网·区块链