第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Pandas (python) 中,如何添加一個包含兩列引用的 groupby 的列

在 Pandas (python) 中,如何添加一個包含兩列引用的 groupby 的列

回首憶惘然 2021-10-12 16:32:51
我正在嘗試向 Pandas GroupBy DataFrame 添加一列。新列(E) 是列(C) 上具有相同鍵(A,B) 的值的總和。該鍵由數(shù)據(jù)幀的另外兩列(A,B) 組成。This is my Dataframe              A   B    C   D0   foo one   1  15  1   bar one   2  10  2   foo two   4  20  3   bar three 4  5   4   foo two   5  6   5   bar two   6  9   6   foo one   7  8    7   foo three 8  15  what I want:     A   B    C  D     E0   foo one   1  15    81   bar one   2  10    22   foo two   4  20    93   bar three 4   5    4 4   foo two   5  6     95   bar two   6  9     66   foo one   7  8     87   foo three 8 15     8這是我的代碼df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',   ...:                           'foo', 'bar', 'foo', 'foo'],   ...:                    'B' : ['one', 'one', 'two', 'three',   ...:                           'two', 'two', 'one', 'three'],   ...:                    'C' : ['1','2','4','4','5','6','7','8'],   ...:                    'D' : ['15','10','20','5','6','9','8','15']})我已經(jīng)嘗試過的df['E'] =df['C'].groupby(df['A,B']).transform('sum') 但不起作用
查看完整描述

2 回答

?
婷婷同學(xué)_

TA貢獻(xiàn)1844條經(jīng)驗 獲得超8個贊

您可以通過 A 和 B 計算 C 的聚合總和,然后將結(jié)果數(shù)據(jù)幀與原始數(shù)據(jù)幀合并


>> df

     A      B  C   D

0  foo    one  1  15

1  bar    one  2  10

2  foo    two  4  20

3  bar  three  4   5

4  foo    two  5   6

5  bar    two  6   9

6  foo    one  7   8

7  foo  three  8  15


df2 = df.groupby(['A','B']).sum().drop(['D'], axis=1).rename(columns={'C':'E'})    


>> df2

           E

A   B       

bar one    2

    three  4

    two    6

foo one    8

    three  8

    two    9

合并df和df2可以得到結(jié)果:


>> df.merge(df2.reset_index(), on=['A', 'B'], how='left')


     A      B  C   D  E

0  foo    one  1  15  8

1  bar    one  2  10  2

2  foo    two  4  20  9

3  bar  three  4   5  4

4  foo    two  5   6  9

5  bar    two  6   9  6

6  foo    one  7   8  8

7  foo  three  8  15  8


查看完整回答
反對 回復(fù) 2021-10-12
  • 2 回答
  • 0 關(guān)注
  • 344 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號