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

Python 3.x 如何使用多索引数据框创建seaborn回归图?,python-3.x,pandas,linear-regression,seaborn,Python 3.x,Pandas,Linear Regression,Seaborn,我有多索引的时间序列数据(年、月),如下所示: print(df.index) print(df) 我想对这些时间序列数据进行非常基本的线性回归。因为pandas.DataFrame.plot不进行任何回归,所以我打算使用Seaborn进行绘图 我试图通过使用lmplot来实现这一点: sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True) 但我有一个错误: TypeError: '>' not suppor

我有多索引的时间序列数据(年、月),如下所示:

print(df.index)
print(df)
我想对这些时间序列数据进行非常基本的线性回归。因为
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
类型


为什么我会收到这个错误?如何解决此问题?

请考虑以下方法:

df['x'] = df.index.get_level_values(0) + df.index.get_level_values(1)/100
收益率:

In [49]: df
Out[49]:
                Value        x
Year Month
2016 3      65.018150  2016.03
     4      63.130035  2016.04
     5      71.071254  2016.05
     6      72.127967  2016.06
     7      67.357795  2016.07
     8      66.639228  2016.08
     9      64.815232  2016.09
     10     68.387698  2016.10
让我们准备X-ticks标签:

labels = df.index.get_level_values(0).astype(str) + '-' + \
         df.index.get_level_values(1).astype(str).str.zfill(2)

sns.lmplot(x='x', y='Value', data=df, fit_reg=True)
ax = plt.gca()
ax.set_xticklabels(labels)
结果:

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

我猜使用
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()

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()