我有一个数据框。两列中的每个单元格都包含一个列表。我想绘制一个 seaborn
-relplot
,其中两列为 x
和 y
。我正在遇到问题
我的代码:
xdf = pd.DataFrame({'v':[[1,2,10,20],[3,4]],'i':[[5,6,50,60],[7,8]]})
xdf['nor_iv'] = ['True','False']
print(xdf)
xdf =
v i nor_iv
0 [1, 2, 10, 20] [5, 6, 50, 60] True
1 [3, 4] [7, 8] False
# Seaborn plot
hue_colors = {'True': 'red',
'False': 'green'}
sns.relplot(data=xdf,x="v", y="i",hue='nor_iv',
markers=True,kind='line',
palette=hue_colors,height=4, aspect=1.5)
plt.show()
当前输出:
TypeError: unhashable type: 'list'
最佳答案
首先使用xdf = xdf.apply(pd.Series.explode)
。请注意,您需要在爆炸后将所需的列从字符串(即 object
)转换为数据类型 int
。以下三种可视化方法:
如果您想要叠加(无行或列):
import matplotlib.pyplot as plt
import seaborn as sns
xdf = pd.DataFrame({'v':[[1,2,10,20],[3,4]],'i':[[5,6,50,60],[7,8]]})
xdf['nor_iv'] = ['True','False']
xdf = xdf.apply(pd.Series.explode)
xdf['v'] = xdf['v'].astype(int)
xdf['i'] = xdf['v'].astype(int)
sns.relplot(data=xdf,x="v", y="i",hue='nor_iv',
markers=True,kind='line',
palette=hue_colors,height=4, aspect=1.5)
plt.show()
如果你想要列,你可以这样做:
import matplotlib.pyplot as plt
import seaborn as sns
xdf = pd.DataFrame({'v':[[1,2,10,20],[3,4]],'i':[[5,6,50,60],[7,8]]})
xdf['nor_iv'] = ['True','False']
xdf = xdf.apply(pd.Series.explode)
xdf['v'] = xdf['v'].astype(int)
xdf['i'] = xdf['v'].astype(int)
sns.relplot(data=xdf,x="v", y="i",col='nor_iv', hue='nor_iv',
markers=True,kind='line',
palette=hue_colors,height=4, aspect=1.5)
plt.show()
如果你想要行,那么:
import matplotlib.pyplot as plt
import seaborn as sns
xdf = pd.DataFrame({'v':[[1,2,10,20],[3,4]],'i':[[5,6,50,60],[7,8]]})
xdf['nor_iv'] = ['True','False']
xdf = xdf.apply(pd.Series.explode)
xdf['v'] = xdf['v'].astype(int)
xdf['i'] = xdf['v'].astype(int)
sns.relplot(data=xdf,x="v", y="i",row='nor_iv', hue='nor_iv',
markers=True,kind='line',
palette=hue_colors,height=4, aspect=1.5)
plt.show()
关于Python 使用 Seaborn Relplot 绘制带有列表单元格的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67512582/