我正在嘗試在 pandas df 中 bool 列的 True 值之間求和所有行的值(實際上是 50 左右的多列),并用總和數填充 True 行。我有一個名稱列,根據名稱是否包含子字串,我創建了一個掩碼布爾列。讓我舉一個直觀的例子。
當前df:
| 面具 | col1 | col2 | col3 |
|---|---|---|---|
| 錯誤的 | 10 | 3 | 5 |
| 錯誤的 | 5 | 2 | 4 |
| 真的 | |||
| 錯誤的 | 5 | 1 | 10 |
| 錯誤的 | 1 | 7 | 6 |
| 錯誤的 | 8 | 2 | 4 |
| 真的 |
期望/目標df:
| 面具 | col1 | col2 | col3 |
|---|---|---|---|
| 錯誤的 | 10 | 3 | 5 |
| 錯誤的 | 5 | 2 | 4 |
| 真的 | 15 | 5 | 9 |
| 錯誤的 | 5 | 1 | 10 |
| 錯誤的 | 1 | 7 | 6 |
| 錯誤的 | 8 | 2 | 4 |
| 真的 | 14 | 10 | 20 |
我使用 for 回圈遍歷 df (更“經典編程”),但它需要永遠,因為 df 通常是數百萬行。我正在尋找一種方法來使用熊貓來做到這一點,因為它非常快。
我也試過這個我在另一篇文章中找到的:(雖然我不熟悉 groupby 和 transform 所以我實際上不知道我做了什么)
col_list = [x for x in df.columns if 'col' in x]
df[col_list] = df.groupby(df['mask'].cumsum()).transfrom('sum').where(df.mask)
但我收到一個錯誤“TypeError:只能將 str(不是“float”)連接到 str”
(資料框中的實際數字是浮點數,但我在示例中使用整數只是為了讓事情變得簡單)
有任何想法嗎?謝謝!
uj5u.com熱心網友回復:
假設空單元格是 NaN,您可以使用:
# start a new group after a True
group = df['mask'].shift(fill_value=False).cumsum()
# get the sum per group transforming all rows
# and fill the NaN of the original dataframe with it
df.combine_first(df.groupby(group).transform('sum'))
輸出:
mask col1 col2 col3
0 False 10.0 3.0 5.0
1 False 5.0 2.0 4.0
2 True 15.0 5.0 9.0
3 False 5.0 1.0 10.0
4 False 1.0 7.0 6.0
5 False 8.0 2.0 4.0
6 True 14.0 10.0 20.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424766.html
上一篇:如何在Python中使用groupby來合并文本,同時保持其他行固定?
下一篇:'FutureWarning:Useof**kwargsisdeprecated,useofengine_kwargs'指的是哪些引數?
