合并重复的列中的单元格

2024-03-28 13:42:37 发布

您现在位置:Python中文网/ 问答频道 /正文


我当前的excel如下所示:

  ----------------
  |  Type |  Val |
  |--------------|
  |  A    |  1   |
  |--------------|     
  |  A    |  2   |     
  |--------------|
  |  B    |  3   |
  |--------------|     
  |  B    |  4   |     
  |--------------|     
  |  B    |  5   |
  |--------------|
  |  C    |  6   |

你知道吗----------------

这是所需的excel:

  ----------------------
  |  Type |  Val | Sum |
  |--------------------|
  |  A    |  1   | 3   |
  |       |------|     |
  |       |  2   |     |
  |--------------------|
  |  B    |  3   | 12  |
  |       |------|     |
  |       |  4   |     |
  |       |------|     |
  |       |  5   |     |
  |--------------------|
  |  C    |  6   |  6  |
  ----------------------

在python中是否可以使用pandas或任何其他模块?你知道吗



Tags: 模块pandastypevalexcelsum
3条回答

你可以用

import pandas as pd

df = pd.DataFrame({'Type': ['A', 'A','B','B','B','C'], 'Val': [1,2 ,3,4,5,6]})

df_result = df.merge(df.groupby(by='Type', as_index=False).agg({'Val':'sum'}).rename(columns={'Val':'Sum'}), on = 'Type')

输出为

print(df_result)
  Type  Val  Sum
0    A    1    3
1    A    2    3
2    B    3   12
3    B    4   12
4    B    5   12
5    C    6    6

这就是你要找的吗?你知道吗

IIUC用途:

df['Sum']=df.groupby('Type').transform('sum')
df.loc[df[['Type','Sum']].duplicated(),['Type','Sum']]=''
print(df)

   Type     Val Sum
0    A        1   3
1             2    
2    B        3  12
3             4    
4             5    
5    C        6   6

备注:您也可以将此添加为索引:

df=df.set_index(['Type','Sum']) #export to excel without index=False

enter image description here

对于合并的前2级,可以将所有3列设置为MultiIndex-只有列的顺序不同:

#specify column name after groupby
df['Sum'] = df.groupby('Type')['Val'].transform('sum')

df = df.set_index(['Type','Sum', 'Val'])
df.to_excel('file.xlsx')

但在我看来,最好的方法是使用重复的值:

df['Sum'] = df.groupby('Type')['Val'].transform('sum')
print (df)

  Type  Val  Sum
0    A    1    3
1    A    2    3
2    B    3   12
3    B    4   12
4    B    5   12
5    C    6    6

df.to_excel('file.xlsx', index=False)

相关问题 更多 >