综合python案例,国家德比火爆程度如何?

wen python案例 2

本文目录导读:

综合python案例,国家德比火爆程度如何?

  1. 案例目标
  2. 第一部分:数据准备(模拟数据生成)
  3. 第二部分:数据清洗与特征工程
  4. 第三部分:经济维度分析(票价与市场价值)
  5. 第四部分:综合可视化(“火爆版图”)
  6. 第五部分:输出总结性结论
  7. 运行结果分析(示例输出)
  8. 扩展思考

这是一份综合性Python案例分析,用于量化分析“国家德比”(以西班牙国家德比——皇家马德里 vs 巴塞罗那为例,数据为模拟/历史参考)的火爆程度。

我们将通过数据爬取(模拟)数据分析可视化三个维度,构建一个“火爆程度评估模型”。


案例目标

  1. 量化热度:分析社交媒体(推特/微博)的提及量、互动量。
  2. 分析经济价值:分析球票价格、转播权费用、赞助商投入。
  3. 对比影响力:对比国家德比与其他顶级赛事(如欧冠决赛、英超曼市德比)的热度指数。
  4. 情感分析:判断球迷对比赛的情绪倾向(正面/负面/中性)。

第一部分:数据准备(模拟数据生成)

由于无法实时抓取真实API,我们用Python生成接近真实分布的模拟数据。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import random
# 设置随机种子,保证结果可复现
random.seed(42)
np.random.seed(42)
# 1. 生成比赛日前后7天的社交媒体提及量数据
dates = pd.date_range(end=datetime.now(), periods=15, freq='D')
teams = ['Real Madrid', 'Barcelona', 'El Clasico']  # 第三个作为标签话题
data = []
for date in dates:
    # 模拟比赛日(第8天)达到峰值
    days_to_match = 7 - (len(dates) - 1 - list(dates).index(date))
    # 使用正态分布模拟爆发式增长和衰减
    if days_to_match == 0:
        base_volume = 500000  # 比赛日当天峰值50万条
    else:
        base_volume = 80000 / (abs(days_to_match) * 2 + 1)  # 距离越远越低
    for team in teams:
        # 添加随机波动
        volume = int(np.random.normal(base_volume, base_volume * 0.2))
        # 正负情绪比例(模拟比赛日更情绪化)
        if days_to_match == 0:
            sentiment = np.random.choice(['Positive', 'Negative', 'Neutral'], p=[0.5, 0.3, 0.2])
        else:
            sentiment = np.random.choice(['Positive', 'Negative', 'Neutral'], p=[0.3, 0.2, 0.5])
        data.append([date, team, max(volume, 0), sentiment])
df_social = pd.DataFrame(data, columns=['Date', 'Team', 'Mentions', 'Sentiment'])
print("社交媒体数据预览:")
print(df_social.head(10))

第二部分:数据清洗与特征工程

计算“热度指数”(Heat Index),综合考量提及量、互动率(模拟)和情感得分。

# 添加模拟的互动量(点赞、转发、评论)
df_social['Engagement'] = df_social['Mentions'] * np.random.uniform(1.5, 3.0, len(df_social))
# 情感得分映射
sentiment_score = {'Positive': 1, 'Neutral': 0, 'Negative': -1}
df_social['Sentiment_Score'] = df_social['Sentiment'].map(sentiment_score)
# 计算综合热度指数 (权重:提及量60%,互动量30%,情感10%)
# 为了平衡量纲,先归一化
df_social['Mentions_Norm'] = (df_social['Mentions'] - df_social['Mentions'].min()) / (df_social['Mentions'].max() - df_social['Mentions'].min())
df_social['Engagement_Norm'] = (df_social['Engagement'] - df_social['Engagement'].min()) / (df_social['Engagement'].max() - df_social['Engagement'].min())
df_social['Heat_Index'] = (df_social['Mentions_Norm'] * 0.6 + 
                           df_social['Engagement_Norm'] * 0.3 + 
                           (df_social['Sentiment_Score'] + 1) / 2 * 0.1) * 100
# 查看比赛日(第8天)的数据
match_day = df_social[df_social['Date'] == df_social['Date'].iloc[7]]
print(f"\n比赛日热点数据:")
print(match_day.groupby('Team')[['Mentions', 'Heat_Index']].sum())

第三部分:经济维度分析(票价与市场价值)

# 模拟票价分布(普通联赛 vs 国家德比)
normal_match_prices = np.random.normal(90, 30, 1000)  # 普通比赛平均90欧
clasico_prices = np.random.normal(350, 150, 1000)     # 国家德比平均350欧
# 球票溢价率
avg_normal = np.mean(normal_match_prices)
avg_clasico = np.mean(clasico_prices)
premium_rate = (avg_clasico - avg_normal) / avg_normal * 100
print(f"\n经济影响力分析:")
print(f"普通比赛平均票价:{avg_normal:.2f} 欧元")
print(f"国家德比平均票价:{avg_clasico:.2f} 欧元")
print(f"溢价率:{premium_rate:.1f}%")
# 转播权费用(每场估算,单位百万欧元)
broadcast_ratio = 4.5  # 国家德比是普通比赛的4.5倍
# 全球收视率(单位:亿人)
global_viewers_clasico = 6.5  # 平均6.5亿
global_viewers_normal = 1.2
print(f"全球收视率对比:德比 {global_viewers_clasico}亿 vs 普通 {global_viewers_normal}亿")

第四部分:综合可视化(“火爆版图”)

# 设置中文和样式
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用于显示中文
plt.rcParams['axes.unicode_minus'] = False
sns.set_style("whitegrid")
fig, axes = plt.subplots(2, 2, figsize=(16, 10))
fig.suptitle('国家德比综合火爆程度分析报告', fontsize=16, fontweight='bold')
# 图1:社交媒体热度时间序列
ax1 = axes[0, 0]
pivot_data = df_social.pivot_table(index='Date', columns='Team', values='Heat_Index', aggfunc='mean')
ax1.plot(pivot_data.index, pivot_data['Real Madrid'], label='皇马', color='#00529F', linewidth=2)
ax1.plot(pivot_data.index, pivot_data['Barcelona'], label='巴萨', color='#A50044', linewidth=2)
ax1.plot(pivot_data.index, pivot_data['El Clasico'], label='标签#ElClasico', color='#FFD700', linewidth=2, linestyle='--')
ax1.axvline(x=match_day['Date'].iloc[0], color='red', linestyle=':', label='比赛日')
ax1.set_title('社交热度趋势(Heat Index)')
ax1.legend()
# 图2:票价分布对比(核密度图)
ax2 = axes[0, 1]
sns.kdeplot(normal_match_prices, fill=True, label='普通联赛', color='gray', ax=ax2)
sns.kdeplot(clasico_prices, fill=True, label='国家德比', color='crimson', ax=ax2)
ax2.set_title('球票价格分布对比')
ax2.set_xlabel('价格(欧元)')
ax2.legend()
# 图3:情感占比饼图
ax3 = axes[1, 0]
sentiment_counts = match_day.groupby('Sentiment').size()
colors = ['#2ecc71', '#e74c3c', '#95a5a6']
wedges, texts, autotexts = ax3.pie(sentiment_counts, 
                                   labels=sentiment_counts.index, 
                                   autopct='%1.1f%%',
                                   colors=colors,
                                   explode=(0, 0.05, 0))
ax3.set_title('比赛日社交情绪分布')
# 图4:多维度对比条形图
ax4 = axes[1, 1]
# 创建对比数据(1=国家德比,0=普通比赛)
metrics = ['社交提及量', '票价溢价', '收视率', '转播权价值']
values = [1, premium_rate/100, global_viewers_clasico/global_viewers_normal, broadcast_ratio]
bars = ax4.barh(metrics, values, color=['#3498db', '#e74c3c', '#f1c40f', '#9b59b6'])
ax4.set_title('火爆程度倍数对比(vs 普通顶级比赛)')
# 添加数值标签
for bar, value in zip(bars, values):
    ax4.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2, 
             f'{value:.2f}x', va='center', fontweight='bold')
plt.tight_layout()
plt.savefig('el_clasico_heat_analysis.png', dpi=150, bbox_inches='tight')
plt.show()

第五部分:输出总结性结论

# 计算最终的综合火爆指数(满分100)
social_score = min(df_social[df_social['Date'] == match_day['Date'].iloc[0]]['Heat_Index'].mean() / 100, 1)
economic_score = min((premium_rate / 200) + (broadcast_ratio / 10), 1)
global_score = min(global_viewers_clasico / 10, 1)
final_index = (social_score * 0.4 + economic_score * 0.35 + global_score * 0.25) * 100
print("\n" + "="*40)
print("国家德比火爆程度综合评估")
print("="*40)
print(f"1. 社交热度得分: {social_score*100:.2f}/100")
print(f"2. 经济热度得分: {economic_score*100:.2f}/100")
print(f"3. 全球影响力得分: {global_score*100:.2f}/100")
print(f"综合火爆指数: {final_index:.2f}/100")
print(f"评级: {'史诗级(超出常规)' if final_index > 85 else '现象级' if final_index > 70 else '热点级'}")
# 结论生成
print("\n结论:国家德比不仅是足球比赛,更是一种全球文化现象。")
print(f"比赛日单日社媒提及量超 {df_social[df_social['Date'] == match_day['Date'].iloc[0]]['Mentions'].sum():,.0f} 条,")
print(f"票价溢价 {premium_rate:.1f}%,收视覆盖 {global_viewers_clasico} 亿人,")
print("其火爆程度在所有体育赛事中处于金字塔尖。")

运行结果分析(示例输出)

  • 社交峰值:比赛日标签提及量约50万+,是平日的6-8倍。
  • 经济效应:票价溢价率通常在200%-400%,转播费约普通比赛的4.5倍。
  • 情感倾向:比赛日“积极”情绪占比高达50%,负面情绪也占30%(由于激烈的对抗性)。
  • 综合指数:通常得出 80-95分,属于“现象级”或“史诗级”热度。

扩展思考

  1. 数据源替换:可以将模拟数据替换为Twitter/微博API、Google Trends数据,实现真实分析。
  2. 自然语言处理(NLP):使用TextBlobtransformers对真实推文进行更精准的情感分析。
  3. 机器学习预测:使用历史数据预测下一场国家德比的热度(时间序列模型如Prophet)。
  4. 地理位置分析:通过IP/标签位置分析热度在全球的分布热力图。

这个案例展示了如何用Python将非结构化数据(社交文本)和结构化数据(票价、收视)结合,构建一个可视化的“热度仪表盘”。

抱歉,评论功能暂时关闭!