簡體   English   中英

Python 根據多個條件將 dataframe 的行添加/合並在一起

[英]Python add / merge rows of a dataframe together based on multiple conditions

下午好,希望你一切都好。

我有一個以下格式的 xlsx 文件,它是 output 來自 Python function 我一直用來解析數據:-

在此處輸入圖像描述

我已將此 xlsx 文件加載到 pandas df 中,以嘗試實現以下 output:-

在此處輸入圖像描述

我要滿足的要求是:- 對於 dataframe 中的每一行,如果“應用程序 ID”和“測試階段”列值匹配,那么我想將這些列值的行值添加在一起並替換原始匹配行,其中一行包含總和值。

如果列值匹配,則原始行應保留在原位。

如果有任何關於如何實現這一目標的指示,將不勝感激。 I have attempted to achieve this code in the function prior to writing the values to the source xlsx output file however I assumed it would be easier to achieve by working with pandas / numpy.

非常感謝吉米

使用groupby_sum

out = df.groupby(['Application ID', 'Test Phase'], as_index=False).sum()
print(out)

# Output
   Application ID Test Phase  Total Tests   A
0               9        SIT           36  36
1              11        UAT            5   5

設置:

data = {'Application ID': [9, 9, 11],
        'Test Phase': ['SIT', 'SIT', 'UAT'],
        'Total Tests': [9, 27, 5],
        'A': [9, 27, 5]}
df = pd.DataFrame(data)
print(df)

# Output
   Application ID Test Phase  Total Tests   A
0               9        SIT            9   9
1               9        SIT           27  27
2              11        UAT            5   5

暫無
暫無

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

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