python-3.x - 如何使用多索引数据框创建 seaborn 回归图?

标签 python-3.x pandas linear-regression seaborn

我有时间序列数据,这些数据在(年,月)上有多重索引,如下所示:

print(df.index)
print(df)
MultiIndex(levels=[[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 4, 5, 6, 7, 8, 9]],
           names=['Year', 'Month'])
            Value
Year Month            
2016 3       65.018150
     4       63.130035
     5       71.071254
     6       72.127967
     7       67.357795
     8       66.639228
     9       64.815232
     10      68.387698

我想对这些时间序列数据进行非常基本的线性回归。因为 pandas.DataFrame.plot不做任何回归,我打算使用 Seaborn 来做我的绘图。

我试图通过使用 lmplot 来做到这一点:
sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True) 

但我收到一个错误:
TypeError: '>' not supported between instances of 'str' and 'tuple'

这对我来说特别有趣,因为 df.index.levels[:] 中的所有元素属于 numpy.int64 类型, df.index.labels[:] 中的所有元素属于 numpy.int8 类型.

为什么我会收到此错误?我该如何解决?

最佳答案

您可以使用 reset_index 将数据框的索引转换为列。然后使用 seaborn 直接绘制 DataFrames 列。

正如我猜测使用 lmplot 的原因将显示不同年份的不同回归(否则 regplot 可能更适合),"Year"列可以用作 hue .

import numpy as np
import pandas as pd
import seaborn.apionly as sns
import matplotlib.pyplot as plt

iterables = [[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]
index = pd.MultiIndex.from_product(iterables, names=['Year', 'Month'])
df = pd.DataFrame({"values":np.random.rand(24)}, index=index)

df2 = df.reset_index()  # or, df.reset_index(inplace=True) if df is not required otherwise 

g = sns.lmplot(x="Month", y="values", data=df2, hue="Year")

plt.show()

enter image description here

关于python-3.x - 如何使用多索引数据框创建 seaborn 回归图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355650/

相关文章:

java - 如何创建预测数据预测区间

python - 如何在 BeautifulSoup 中找到 `td` 父标签的所有 `tr` 且具有 `class="Accordion-toggle main-row"' 的父标签?

python - 无法在 pygame 中生成多个敌人

python - 解析此序列的最佳方法?

python - pandas dataframe 将列值附加到另一个具有列表元素的 pandas 列

python - 不选择缺失值吗?

python - 如何在 python 中检测不正确的 kwarg 名称

r - 将蒙特卡罗 p 值排列成不同样本大小和方差估计量的矩阵

python-3.x - 如何使用 AWS CDK 中的 Invoke Lambda 将 JSON 传递到 AWS Step Function 中的 lambda

python - pd.get_dummies 与在 statsmodel ols 中简单包含分类变量相同吗?