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

Python绘制Period类型季度列与整数列的回归线问题求助

问题:Period格式日期列无法绘制回归线

我无法为包含Period格式日期列和整数列的简单DataFrame绘制回归线。示例DataFrame创建代码如下:

df = pd.DataFrame({"quarter": ['2017Q1', '2017Q2', '2017Q3', '2017Q4', 
                               '2018Q1', '2018Q2', '2018Q3', '2018Q4'],
               
               "total": [392, 664, 864,1024,
                        1202, 1375, 1532, 1717]
})
    
df["quarter"] = pd.to_datetime(df["quarter"]).dt.to_period('Q')

使用以下代码生成回归图时:

import seaborn as sns
import matplotlib.pyplot as plt

ax = sns.regplot(
    data=df,
    x='quarter',
    y='total',
)

plt.show();

出现错误:

TypeError: float() argument must be a string or a number, not 'Period'

将Period列转换为字符串/对象格式或整数格式均未解决问题,求绘制total与quarter的回归趋势线的方法。

解决方案

Seaborn的regplot要求x轴输入为数值类型,Period对象无法直接转换为浮点数,因此需要将日期周期转换为可计算的数值,以下是几种可行方法:

方法1:使用Period的ordinal值

Period对象的ordinal属性会返回该周期在时间序列中的序号(从1开始的整数),可直接作为x轴输入:

# 添加ordinal列
df['quarter_ordinal'] = df['quarter'].apply(lambda x: x.ordinal)

# 绘制回归图
ax = sns.regplot(
    data=df,
    x='quarter_ordinal',
    y='total',
)

# 将x轴刻度替换为原季度标签
ax.set_xticks(df['quarter_ordinal'])
ax.set_xticklabels(df['quarter'])
plt.show()

方法2:转换为datetime并提取时间戳数值

将Period转换为季度起始/结束日期的datetime对象,再转为时间戳数值:

# 将Period转换为季度起始日期的datetime,再转为秒级时间戳
df['quarter_timestamp'] = df['quarter'].dt.start_time.astype('int64') // 10**9

# 绘制回归图
ax = sns.regplot(
    data=df,
    x='quarter_timestamp',
    y='total',
)

# 替换x轴刻度为原季度标签
ax.set_xticks(df['quarter_timestamp'])
ax.set_xticklabels(df['quarter'])
plt.show()

方法3:使用连续索引作为数值

如果季度是连续排列的,可直接用DataFrame的索引作为x轴数值,再替换刻度标签:

# 绘制回归图,用索引作为x值
ax = sns.regplot(
    data=df,
    x=df.index,
    y='total',
)

# 设置x轴刻度和标签
ax.set_xticks(df.index)
ax.set_xticklabels(df['quarter'])
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:48:21