Python 使用 Seaborn Relplot 绘制带有列表单元格的数据框

标签 python pandas dataframe matplotlib seaborn

我有一个数据框。两列中的每个单元格都包含一个列表。我想绘制一个 seaborn-relplot ,其中两列为 xy。我正在遇到问题

我的代码:

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

enter image description here

如果你想要列,你可以这样做:

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

enter image description here

如果你想要行,那么:

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

enter image description here

关于Python 使用 Seaborn Relplot 绘制带有列表单元格的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67512582/

相关文章:

python - Pandas:如何删除系列中的非字母数字列

python - 如何在 Django 中配置 Python 日志记录模块?

python - 什么是更 Pythonic 的方法来测试我的部分代码?

python - python是如何实现拼接的?

python - 如何将带有文本信息的1.3 GB csv文件读取到Python的pandas对象中?

python - Convert_to_r_dataframe 给出错误 no attribute dtype

python - 如何通过字符串值和行中匹配的整数来过滤 Pandas 数据框?

python - AbstractBaseUser 电子邮件作为用户名验证

python - pandas 数据框按索引和整数

python - 如何在 Excel/csv 中保存数据帧值