合并列的重复单元格

Hit*_*mar 2 python excel dataframe pandas


我当前的 Excel 看起来像:

  ----------------
  |  Type |  Val |
  |--------------|
  |  A    |  1   |
  |--------------|     
  |  A    |  2   |     
  |--------------|
  |  B    |  3   |
  |--------------|     
  |  B    |  4   |     
  |--------------|     
  |  B    |  5   |
  |--------------|
  |  C    |  6   |
Run Code Online (Sandbox Code Playgroud)

----------------

这是所需的Excel:

  ----------------------
  |  Type |  Val | Sum |
  |--------------------|
  |  A    |  1   | 3   |
  |       |------|     |
  |       |  2   |     |
  |--------------------|
  |  B    |  3   | 12  |
  |       |------|     |
  |       |  4   |     |
  |       |------|     |
  |       |  5   |     |
  |--------------------|
  |  C    |  6   |  6  |
  ----------------------
Run Code Online (Sandbox Code Playgroud)

Python 中是否可以使用 Pandas 或任何其他模块?


ank*_*_91 5

IIUC 用途:

df['Sum']=df.groupby('Type').transform('sum')
df.loc[df[['Type','Sum']].duplicated(),['Type','Sum']]=''
print(df)
Run Code Online (Sandbox Code Playgroud)
   Type     Val Sum
0    A        1   3
1             2    
2    B        3  12
3             4    
4             5    
5    C        6   6
Run Code Online (Sandbox Code Playgroud)

PS:您还可以将其添加为索引:

df=df.set_index(['Type','Sum']) #export to excel without index=False
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述