熊猫:如何绘制特定的列和案例?

时间:2020-09-28 08:37:09

标签: python pandas

我有一个如下所示的数据框

    Zone    year    Intervention A  Intervention B
0   Zone 1  2005    0.896788        0.892161
1   Zone 1  2006    0.807323        0.809103
2   Zone 1  2007    0.758814        0.764219
3   Zone 2  2005    0.697728        0.699586
4   Zone 2  2006    0.649360        0.648350
5   Zone 2  2017    0.566785        0.571259

我想绘制4条不同的曲线,其中在x轴上我有year,在y-axis上有间隔的值。

4条曲线是:

Intervention A Zone 1

Intervention A Zone 2

Intervention B Zone 1

Intervention B Zone 2

1 个答案:

答案 0 :(得分:0)

第一个想法是使用DataFrame.pivot并展平MultiIndex in columns

df1 = df.pivot(index='year', columns='Zone')
df1.columns = df1.columns.map('_'.join)

df1.plot()

另一种方法是分别过滤每个subDataFrame:

df11 = df.loc[df['Zone'].eq('Zone 1')]
df22 = df.loc[df['Zone'].eq('Zone 2')]

ax = df11.plot(x='year', y='Intervention A')
df22.plot(x='year', y='Intervention A', ax=ax)
df11.plot(x='year', y='Intervention B', ax=ax)
df22.plot(x='year', y='Intervention B', ax=ax)