首页 > 解决方案 > 绘制具有相同列的 2 个熊猫数据框

问题描述

我有 2 个长度相同且列名相同的熊猫数据框。我想循环遍历列并将列相互绘制 - df1 中的 column1 与 df2 中的 col1 对比。我想要条形图

df1:

   A  B  C
1  0  4  8
2  5  6  9
3  2  5  1

df2:

   A  B  C
1  9  4  5
2  1  4  2
3  5  5  1

标签: pythonpandasmatplotlib

解决方案


也许像下面这样,不太清楚你所说的条形图是什么意思,我现在并排绘制

df1=pd.DataFrame({'A':[0,5,2],'B':[4,6,5],'C':[8,9,1]})
df2=pd.DataFrame({'A':[9,1,5],'B':[4,4,5],'C':[5,2,1]})

fig,ax = plt.subplots(1,3,figsize=(8,5))
x1 = [i-0.1 for i in range(len(df1))]
x2 = [i+0.1 for i in range(len(df2))]
for i,col in enumerate(df1.columns):
    ax[i].bar(x=x1,height=df1[col],width=0.2,label="df1")
    ax[i].bar(x=x2,height=df2[col],width=0.2,label="df2")
    ax[i].legend()

在此处输入图像描述


推荐阅读