You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据转为数值型以通过matplotlib可视化?含具体场景需求

解决方案:DataFrame数据转换与Matplotlib可视化

1. 先处理fatalities列的数值转换

根据需求,先把fatalities的分类值(致命/仅受伤/无伤亡)转成数值,方便后续统计。假设该列的取值为['Fatal', 'Injured', 'None'],可以用映射快速转换:

import pandas as pd
import matplotlib.pyplot as plt

# 转换日期列(如果还不是日期格式)
df['incident_date'] = pd.to_datetime(df['incident_date'])

# 映射分类值为数值:2=致命,1=仅受伤,0=无伤亡
df['fatality_code'] = df['fatalities'].map({
    'Fatal': 2,
    'Injured': 1,
    'None': 0
})

# 额外生成受伤标记列(用于统计受伤事件总数)
df['has_injury'] = df['fatality_code'].apply(lambda x: 1 if x >=1 else 0)

2. 统计受伤事件数量并可视化

统计各类事件分布(含受伤/致命/无伤亡)

用柱状图直观展示不同类型事件的数量:

event_dist = df['fatalities'].value_counts()

plt.figure(figsize=(8,5))
event_dist.plot(kind='bar', color=['#e63946', '#457b9d', '#1d3557'])
plt.title('事件类型数量统计')
plt.xlabel('事件类型')
plt.ylabel('事件数量')
plt.xticks(rotation=0)
plt.show()

单独统计受伤事件总数

如果只需要看受伤(含致命)的总数量,用简单柱状图展示:

total_injured = df['has_injury'].sum()

plt.figure(figsize=(6,4))
plt.bar(['受伤事件总数'], [total_injured], color='#e63946')
plt.title('受伤事件总数统计')
plt.ylabel('事件数量')
plt.show()

3. 展示死亡人数最多的日期

先按日期分组统计致命事件的数量,再找到峰值日期并可视化:

# 按日期统计致命事件数量
daily_fatal = df[df['fatalities'] == 'Fatal'].groupby('incident_date')['fatalities'].count()

# 找到峰值日期和数量
peak_date = daily_fatal.idxmax()
peak_count = daily_fatal.max()

# 绘制趋势图并标记峰值
plt.figure(figsize=(12,6))
daily_fatal.plot(kind='line', marker='o', color='#e63946')
plt.scatter(peak_date, peak_count, color='#ffbe0b', s=120, zorder=5, 
            label=f'死亡事件最多日期: {peak_date.date()}\n数量: {peak_count}')
plt.title('每日致命事件数量趋势')
plt.xlabel('日期')
plt.ylabel('致命事件数量')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

关键提示

  • 如果你的fatalities列实际取值和示例不同,记得修改映射字典里的键值,匹配真实数据
  • 确保incident_date是日期格式,否则分组统计会出错

内容的提问来源于stack exchange,提问作者Airin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 03:46:07