如何根据另一列中的重复值在一列中添加行,并最终在python中保留第一行?

new*_*bee 3 python calculated-columns addition dataframe pandas

我对 python pandas 模块非常陌生。

假设我有一个数据框或表格如下:

 df = pd.DataFrame({
        'Column A': [12,12,12, 15, 16, 141, 141, 141, 141],
         'Column B':['Apple' ,'Apple' ,'Apple' , 'Red', 'Blue', 'Yellow', 'Yellow', 'Yellow', 'Yellow'],
        'Column C':[100, 50, np.nan , 23 , np.nan , 199 , np.nan , 1,np.nan]
    }) 
Run Code Online (Sandbox Code Playgroud)

或者我有一个数据表如下:


    | Column A | Column B |Column C 
----| -------- | ---------|--------
0   | 12       | Apple    |100     
1   | 12       | Apple    |50      
2   | 12       | Apple    |NaN      
3   | 15       | Red      |23       
4   | 16       | Blue     |NaN      
5   | 141      | Yellow   |199      
6   | 141      | Yellow   |NaN      
7   | 141      | Yellow   |1        
8   | 141      | Yellow   |NaN  


Run Code Online (Sandbox Code Playgroud)
  • 如果A列中的值重复,则将C列中的相应值相加,并将总和粘贴到新的D列中(例如,12有3行,因此我们应该添加相应的值100 + 50 + NaN,求和结果150 应存储在新的 D 列中。

  • 如果 A 列中的值不重复,请直接将 C 列值粘贴到新 D 列(例如第 3 行)中,但对于 NaN,它应该为 0(例如第 4 行)。

你能帮我在 python jupyter 笔记本中获得这样的输出吗:

      | Column A | Column B |Column C |Column D 
----- | -------- | ---------|---------|---------
 0    | 12       | Apple    |100      |150      
 1    | 15       | Red      |23       |23       
 2    | 16       | Blue     |NaN      |0        
 3    | 141      | Yellow   |199      |200  

Run Code Online (Sandbox Code Playgroud)

d.b*_*d.b 5

df.groupby("Column A", as_index=False).agg(B=("Column B", "first"),
                                           C=("Column C", "first"),
                                           D=("Column C", "sum"))
#      Column A         B         C         D
# 0          12     Apple     100.0     150.0
# 1          15       Red      23.0      23.0
# 2          16      Blue       NaN       0.0
# 3         141    Yellow     199.0     200.0
Run Code Online (Sandbox Code Playgroud)