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

Python时间序列与浮点列可视化:时间-速度关系分析及绘图报错排查

问题解决:hours列类型转换与回归图绘制

1. 先排查hours列的实际内容

先运行以下代码确认hours列的类型和具体格式,方便后续针对性处理:

print(df['hours'].dtype)
print(df['hours'].sample(10))

2. 根据不同格式转换数据类型

情况1:hours是字符串格式的纯小时数(比如"8", "14")

直接转成数值型,同时清理无效值:

df['hours'] = pd.to_numeric(df['hours'], errors='coerce')
# 删除hours或speed列存在空值的行
df = df.dropna(subset=['hours', 'speed'])

情况2:hours是完整时间格式(比如"08:30:00", "14:15")

先转成时间类型,再提取小时部分:

df['hours'] = pd.to_datetime(df['hours'], errors='coerce').dt.hour
df = df.dropna(subset=['hours', 'speed'])

情况3:hours是带描述的自定义格式(比如"上午9点")

用正则提取数字部分再转成数值:

import re
df['hours'] = df['hours'].apply(lambda x: re.findall(r'\d+', str(x))[0] if re.findall(r'\d+', str(x)) else None)
df['hours'] = pd.to_numeric(df['hours'], errors='coerce')
df = df.dropna(subset=['hours', 'speed'])

3. 重新绘制回归图

处理完类型后,重新运行代码即可生成回归图:

sns.lmplot(x="hours", y="speed", data=df)
plt.title('Hours vs Internet Speed Regression')
plt.xlabel('Hour of Day')
plt.ylabel('Internet Speed')
plt.show()

完整分析思路

1. 时间与速度的关联分析

  • 除线性回归图外,用箱线图查看不同小时段的速度分布差异:
    plt.figure(figsize=(12,6))
    sns.boxplot(x='hours', y='speed', data=df)
    plt.title('Speed Distribution by Hour of Day')
    plt.show()
    
  • 计算各小时段的平均速度,用柱状图直观展示趋势:
    hourly_speed = df.groupby('hours')['speed'].mean().reset_index()
    plt.figure(figsize=(12,6))
    sns.barplot(x='hours', y='speed', data=hourly_speed)
    plt.title('Average Speed by Hour of Day')
    plt.show()
    

2. 确定一天中的最佳联网时段

  • 从上述统计结果中,筛选速度均值/中位数最高的小时段;
  • 用方差分析验证不同小时段的速度是否存在显著差异,确认时段的可靠性:
    from scipy.stats import f_oneway
    # 按小时分组提取速度数据
    groups = [df[df['hours'] == h]['speed'] for h in df['hours'].unique()]
    f_stat, p_value = f_oneway(*groups)
    print(f"ANOVA F-statistic: {f_stat}, p-value: {p_value}")
    # 若p值<0.05,说明不同小时段的速度差异具有统计学意义
    

3. 分析关联关系是否随年份变化

  • 先从日期列(假设数据中有date列)提取年份:
    df['year'] = pd.to_datetime(df['date']).dt.year
    
  • 分年份绘制回归图和趋势对比图:
    # 分年份的线性回归子图
    sns.lmplot(x="hours", y="speed", data=df, col='year', col_wrap=2)
    plt.show()
    
    # 分年份的小时平均速度折线对比图
    yearly_hourly = df.groupby(['year', 'hours'])['speed'].mean().reset_index()
    plt.figure(figsize=(14,8))
    sns.lineplot(x='hours', y='speed', hue='year', data=yearly_hourly, marker='o')
    plt.title('Hourly Average Speed by Year')
    plt.show()
    
  • 计算不同年份的小时-速度相关系数,量化关联程度的变化:
    yearly_corr = df.groupby('year').apply(lambda x: x['hours'].corr(x['speed']))
    print(yearly_corr)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:25:28