python数据分析1

​Pandas 数据处理与可视化实战指南

csv文件可下载

1. 数据读取与基础检查​

import pandas as pd
import os

# 方法1:原始字符串路径
file_path = r'C:\Users\admin\Desktop\Video_Games_Sales.csv'
if os.path.exists(file_path):
    try:
        raw_data = pd.read_csv(file_path, encoding='gbk')  # 尝试常见编码
        print("数据前5行:\n", raw_data.head())
    except Exception as e:
        print(f"读取失败!错误:{e}")
else:
    print("文件路径错误!")

#方法2:
raw_data = pd.read_excel(r'C:\Users\admin\Desktop\pandas练习文件数据.xlsx')
print(data)

2. 数据操作技巧​

增删改查​
# 新增列:NA与EU销量总和
raw_data['NA_EU'] = raw_data['NA_Sales'] + raw_data['EU_Sales']

# 删除列(需重新赋值)
raw_data = raw_data.drop('NA_EU', axis=1)  

# 条件查询:2017年Sega发布的游戏
sega_games = raw_data.loc[
    (raw_data['Year_of_Release'] == 2017) & 
    (raw_data['Publisher'] == 'Sega'),
    ['Name', 'Publisher']
]
缺失值处理​
# 方法1:删除缺失值
clean_data = raw_data.dropna()

# 方法2:填充均值/众数
mean_score = raw_data['Critic_Score'].mean()
raw_data['Critic_Score'].fillna(mean_score, inplace=True)

3. 统计与分组​

分组聚合​
# 单分组:每年最高销量
max_sales = raw_data.groupby('Year_of_Release')['Global_Sales'].max()

# 多分组:每年各发行商的销量极值
result = raw_data.groupby(['Year_of_Release', 'Publisher'])[['Global_Sales']].agg(['max', 'min'])
自定义函数应用
def top3_sales(group):
    return group.nlargest(3, 'Global_Sales')

# 按发行商分组取销量TOP3
top_games = raw_data.groupby('Publisher', group_keys=False).apply(top3_sales)

​4. 数据可视化

柱状图:年度游戏发行量​
import matplotlib.pyplot as plt

# 筛选2010年后数据并统计
year_counts = raw_data[raw_data['Year_of_Release'] >= 2010]['Year_of_Release'].value_counts().reset_index()
year_counts.columns = ['Year', 'Count']

# 绘图
year_counts.plot(
    x='Year', y='Count', kind='bar',
    title='年度游戏发行量(2010年后)',
    figsize=(10, 5),
    color='#4CAF50'
)
plt.grid(axis='y', linestyle='--', alpha=0.5)
plt.show()

双柱状图:销量极值对比​

# 合并最大/最小销量
result = pd.concat([
    raw_data.groupby('Year_of_Release')['Global_Sales'].max(),
    raw_data.groupby('Year_of_Release')['Global_Sales'].min()
], axis=1)
result.columns = ['Max_Sales', 'Min_Sales']

# 绘图
result.plot(kind='bar', figsize=(12, 6), color=['#1f77b4', '#ff7f0e'])
plt.title('年度游戏销量极值对比')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

你可能感兴趣的:(python,数据分析,开发语言)