簡體   English   中英

使用 pandas groupby 除當前行之外的兩列之間創建一個新列

[英]create a new column with pandas groupby division between two columns excluding the current row

我想用 pandas groupby 在除當前行之外的兩列之間的划分創建一個新列。 樣本數據集:

import pandas as pd
  
df = pd.DataFrame({'Group':['A', 'A', 'A', 'B', 'B'],
                     'Col_1':[100, 200, 300, 400, 500],
                     'Col_2':[55, 66, 77, 88, 99]})
團體 Col_1 Col_2
一個 100 55
一個 200 66
一個 300 77
400 88
500 99

我想創建一個名為“Div_excl”的新列

方法:每個Group取Col_1和Col_2之和,然后排除每個groupby sum內的當前行值,再做除法

| Group |Col_1 | Col_2  |                Div_exclud             |
|-------|------|--------|---------------------------------------|
|    A  | 100  |  55    |[(55+66+77)-55)] / [(100+200+300)-100)]|
|    A  | 200  |  66    |[(55+66+77)-66)] / [(100+200+300)-200)]|
|    A  | 300  |  77    |[(55+66+77)-77)] / [(100+200+300)-300)]|
|    B  | 400  |  88    |   [(88+99)-88)] / [(400+500)-400)]    |
|    B  | 500  |  99    |   [(88+99)-99)] / [(400+500)-500)]    |

我嘗試了以下方法,但看起來不正確:

df.groupby('Group').apply(lambda x: (df['Col_2'].sum()-x)/(df['Col_1'].sum()-x))

嘗試transform

g = df.groupby('Group')
df['New'] = (g['Col_2'].transform('sum')-df.Col_2)/(g['Col_1'].transform('sum')-df.Col_1)
df
Out[339]: 
  Group  Col_1  Col_2       New
0     A    100     55  0.286000
1     A    200     66  0.330000
2     A    300     77  0.403333
3     B    400     88  0.198000
4     B    500     99  0.220000

這是您已經在使用的一種通過apply的替代方法:

df = (
    df.groupby('Group')
    .apply(
        lambda x: x.assign(
            Div_exclud=(x['Col_2'].sum()-x['Col_2'])/(x['Col_1'].sum()-x['Col_1']))
    )
    .reset_index(drop=True)
)

OUTPUT:

  Group  Col_1  Col_2  Div_exclud
0     A    100     55    0.286000
1     A    200     66    0.330000
2     A    300     77    0.403333
3     B    400     88    0.198000
4     B    500     99    0.220000

暫無
暫無

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

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