簡體   English   中英

從熊貓數據框中的唯一行值創建新列

[英]Create new columns from unique row values in a pandas dataframe

我有一個熊貓數據框,如:

    yearPassed  policyType  count
0       1990        1        2000
1       1990        2        1400
2       1990        3        1200
3       1991        3        70
4       1992        2        1000
5       1992        3        800

我想制作一個條形圖,按policyType列進行顏色編碼,並在X軸上顯示Year,在Y軸上顯示count。

我嘗試這樣做:

policy_vs_year.plot(x="yearPassed", y=["count", "policyType"], kind="bar")
plt.show()

但這給出了非常糟糕的情節。

因此,我決定將我的數據框轉換為如下所示(也許這樣繪制更容易):

    yearPassed       1       2       3
0       1990       2000    1400     1200
1       1991        0        0       70
2       1992        0      1000     800

我的問題是,大熊貓的基本功能是否有可能實現這一目標? (或者有更簡單的選擇以原始格式繪制數據框-無需重新格式化?)

使用df.pivot_table可以輕松完成此操作:

df = df.pivot_table(index=['yearPassed'], 
            columns=['policyType'], values='count').fillna(0)
df

policyType       1       2       3
yearPassed                        
1990        2000.0  1400.0  1200.0
1991           0.0     0.0    70.0
1992           0.0  1000.0   800.0

此外,可以使用df.plot制作堆疊的條形圖:

import matplotlib.pyplot as plt
df.plot(kind='bar', stacked=True)
plt.show()

在此處輸入圖片說明

只用pandas

df.set_index(['yearPassed','policyType']).unstack(-1).fillna(0).plot.bar(stacked=True)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM