gpt4 book ai didi

python - 使用 Pandas 绘制包含列表的列

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:46 25 4
gpt4 key购买 nike

我有一个包含多列的数据框 (df),其中两列在每一行中存储一个列表:

Index    list1                             list2
A [ 0.09173306 0.12331911 0.20057651 ] [ 0.3128322 0.27153913 ]
D [ 0.03861522 0.10524985 ] [ 0.37265687 0.48347806 ]
E [ 0.02124905 0.01149118 ] [ 0.04348405 0.17057435 0.37838683 0.37481453 ]

我想使用 pandas 内置的 plot 函数将这些列表绘制成条形图。

使用

df.list1.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax)

我可以绘制每个列表的第一个元素。然而,尝试

df.list1.plot(kind='bar', width=0.9, ax=bar_ax)

导致以下错误:

Empty 'DataFrame': no numeric data to plot

我想做的是,(1) 将两个列表绘制成一个图,如下所示:

df[['list1','list2']].plot(kind='bar', width=0.9, ax=bar_ax)

(2) 也只将每个列表的第一个元素绘制到一个条形图中,我可以这样做:

df.list1.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax, color='blue')
df.list2.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax, color='red')

但是,这会导致条形图被绘制在彼此之上(不是堆叠!)——我想将它们分组。

最佳答案

考虑这个包含值的 DF 列表,如下所示:

np.random.seed(42)
df = pd.DataFrame({'list1': np.random.randint(0, 10, (5,2)).tolist(),
'list2': np.random.randint(0, 10, (5,3)).tolist()},
index=list('ABCDE'))

Image

Q-1 将两个列表绘制成一个图:

拆开 DF 使列名显示为索引,并使列表中的各个值出现在各个系列对象中。

df_lists = df[['list1','list2']].unstack().apply(pd.Series)
df_lists.plot.bar(rot=0, cmap=plt.cm.jet, fontsize=8, width=0.7, figsize=(8,4))

Image

Q-2 仅将每个列表的第一个元素绘制成一个单独的分组条形图:

使用DF.applymap选择所需列的第一个元素以获得分组条形图。

df[['list1','list2']].applymap(lambda x: x[0]).plot.bar(rot=0, color=list('br'))

Image

关于python - 使用 Pandas 绘制包含列表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40256820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com