簡體   English   中英

如何使用Python Pandas進行匯總,獲取百分比並重新分配列和行?

[英]How to aggregate, obtain percentage, and reassign column and row with Python Pandas?

我有三列“ A”(接受)和“ D”(拒絕)“ Decision”,以及年份和月份

Decision   Year   Month
A   2003   1
A   2005   3
D   2005   2
D   2003   3
A   2004   1

我想根據Decision ='A'的計數對其進行重組,然后以Year為索引並將每個月作為一列創建一個新的df。 注意:每個單元格現在變為否。 該年和月中“ A”的含義

Year Month1 Month2 Month3 ...    
2002   1   3   4
2003   2   4   5
2004   2   3   5
2005   5   3   42
2006   4   2   12

類似地,我想要決策='D'的另一個df

Year Month1 Month2 Month3 ...    
2002   4   4   3
2003   2   4   23
2004   4   1   12
2005   4   2   31
2006   4   2   22

但最終,我希望每個單元格為(編號“ A”)/(編號“ A” +編號“ D”)的百分比

Year Month1 Month2 Month3 ...    
2002   .2   .43   .57
2003  (etc)
2004  (etc)
2005   (etc)
2006   (etc)

我曾嘗試對熊貓進行groupby嘗試,但沒有成功,我想我可以創建不同的列表來獲取計數,然后將這些列表合並在一起以創建df,但是我想知道熊貓是否有更簡單的方法。

通過使用normalize=Truegroupby使用value_counts

d1 = df.groupby(['Year', 'Month']).Decision.value_counts(normalize=True)
d1.xs('A', level='Decision').unstack('Month', fill_value=0).add_prefix('Month')

Month    Month1    Month2    Month3
Year                               
2002   0.200000  0.428571  0.571429
2003   0.400000  0.666667  0.416667
2004   0.285714  0.300000  0.312500

設定

df = pd.DataFrame(dict(
        Decision=['A'] * 29 + ['D'] * 46,
        Year=[2002] * 8 + [2003] * 11 + [2004] * 10
           + [2002] * 11 + [2003] * 12 + [2004] * 23,
        Month=[
            1, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3,
            1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3,
            3, 3, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1,
            2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
    ))[['Decision', 'Year', 'Month']]

這將為您提供最終結果,而無需構建2個中間DF。

#use groupby, count As and get percentage, finally pivot month to columns.
df.groupby(by=['Year','Month'])['Decision'].apply(lambda x: len(x[x=='A'])/float(len(x))).reset_index(level=1).pivot(columns='Month').fillna(0)
Out[257]: 
      Decision          
Month        1    2    3
Year                    
2003       1.0  0.0  0.0
2004       1.0  0.0  0.0
2005       0.0  0.0  1.0

暫無
暫無

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

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