我有这个数据框:
Ind1 Ind2 M F
Business Analyst 1-2 years 50 55
Business Analyst 10-20 years 47 23
DBA Engineer 1-2 years 31 12
DBA Engineer 10-20 years 21 10
我想分别计算 M 和 F 的总数,并将其插入到唯一职业条目的末尾(在本例中为第二行)。数据帧是多索引的(Ind1 和 Ind2)。 所以我的最终数据框应该是:
Ind1 Ind2 M F
Business Analyst 1-2 years 50 55
Business Analyst 10-20 years 47 23
Total Not required 97 78
DBA Engineer 1-2 years 31 12
DBA Engineer 10-20 years 21 10
Total Not required 52 22
我怎样才能在pandas中做到这一点?我无法正确地对此进行编码。
注意:新行应该是索引的一部分(即在索引内部)。
最佳答案
一种方法是对 Ind1
上的数据帧进行groupby
并使用sum
进行聚合,然后将此聚合数据帧附加到df
并对 Ind1
上的值进行排序
:
df1 = df.append(df.groupby('Ind1', as_index=False).sum()\
.assign(Ind2='Not Required')).sort_values('Ind1', ignore_index=True)
df1.loc[df1['Ind2'].eq('Not Required'), 'Ind1'] = 'Total'
另一种类似的方法,但这里我们单独处理 df 中的每个分组帧,然后连接所有分组帧:
f = lambda g: g.append({'Ind1': 'Total', 'Ind2': 'Not Required', **g[['M','F']].sum()}, ignore_index=True)
df1 = pd.concat([f(g) for _, g in df.groupby('Ind1')], ignore_index=True)
结果:
Ind1 Ind2 M F
0 Business Analyst 1-2 years 50 55
1 Business Analyst 10-20 years 47 23
2 Total Not Required 97 78
3 DBA Engineer 1-2 years 31 12
4 DBA Engineer 10-20 years 21 10
5 Total Not Required 52 22
关于python - 在列出总共两列的每第二行之后插入索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65447729/