我在python中有这样一个DataFrame
name id Background Complexion Ear Ear Accessories
Li1 3800 White Clean Ape Ear None
Lio2 5700 Purple Galaxy Clean Ape Ear Silver Earring
Lio4 8400 Green Clean Orc Ear Spiky Earring
Noam 3000 Noir Galaxy Clean Ape Ear Silver Earring
AVERSE 6100 Grey Galaxy Clean Ape Ear Gender Earring
我想计数每个单元格,除了两个第一个colmn 'name‘和'id’,最后创建一个这样的表
name id Background Complexion Ear Ear Accessories
Li1 3800 1 5 4 1
Lio2 5700 1 5 4 2
Lio4 8400 1 5 1 1
Noam 3000 1 5 4 2
AVERSE 6100 1 5 4 1
并计算这个数字的公式(例如+3),然后我们有
name id Background Complexion Ear Ear Accessories
Li1 3800 4 8 7 4
Lio2 5700 4 8 7 5
Lio4 8400 4 8 4 4
Noam 3000 4 8 7 5
AVERSE 6100 4 8 7 4
和每一行的和数
name id Background Complexion Ear Ear Accessories sum
Li1 3800 4 8 7 4 23
Lio2 5700 4 8 7 5 24
Lio4 8400 4 8 4 4 20
Noam 3000 4 8 7 5 24
AVERSE 6100 4 8 7 4 23
在巨蟒中,熊猫怎么能做到这一点呢?
发布于 2022-04-03 07:43:13
IIUC,您需要循环以执行每列的计数。您可以使用groupy.transform('count')
。其余的是简单的向量操作(add
/sum
):
cols = ['name', 'id']
df2 = (df[cols]
.join(pd.DataFrame({c: df.groupby(c)[c].transform('count')
for c in df.drop(columns=cols).columns})
.add(3)
.assign(sum=lambda d: d.sum(1))
)
)
产出:
name id Background Complexion Ear Ear Accessories sum
0 Li1 3800 4 8 7 4 23
1 Lio2 5700 4 8 7 5 24
2 Lio4 8400 4 8 4 4 20
3 Noam 3000 4 8 7 5 24
4 AVERSE 6100 4 8 7 4 23
https://stackoverflow.com/questions/71727155
复制相似问题