我正在尝试使用两个相同的DataFrames (预测和观察)绘制具有完全相同的结构的子图……第一列是索引
下面的代码在使用pd.melt和merge进行连接时创建新的索引,如图所示,橙色线的索引从1-5更改为6-10
我想知道是否有人可以修复下面的代码,以保持橙色行的相同索引:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
actual = pd.DataFrame({'a': [5, 8, 9, 6, 7, 2],
'b': [89, 22, 44, 6, 44, 1]})
predicted = pd.DataFrame({'a': [7, 2, 13, 18, 20, 2],
'b': [9, 20, 4, 16, 40, 11]})
# Creating a tidy-dataframe to input under seaborn
merged = pd.concat([pd.melt(actual), pd.melt(predicted)]).reset_index()
merged['category'] = ''
merged.loc[:len(actual)*2,'category'] = 'actual'
merged.loc[len(actual)*2:,'category'] = 'predicted'
g = sns.FacetGrid(merged, col="category", hue="variable")
g.map(plt.plot, "index", "value", alpha=.7)
g.add_legend();

发布于 2018-12-15 05:12:04
橙色行('variable' == 'b')没有0-5索引,这是因为您使用melt的方式。如果你看一下pd.melt(actual),索引与你的预期不符。
下面是我如何重新排列数据帧的方法:
merged = pd.concat([actual, predicted], keys=['actual', 'predicted'])
merged.index.names = ['category', 'index']
merged = merged.reset_index()
merged = pd.melt(merged, id_vars=['category', 'index'], value_vars=['a', 'b'])发布于 2020-11-16 17:19:33
将ignore_index变量设置为false以保留索引。
df = df.melt(var_name=‘species’, value_name=‘height’, ignore_index = False)
https://stackoverflow.com/questions/53785824
复制相似问题