添加列,其中包含具有任意值的其他列的计数

问题描述 投票:0回答:2

我的数据框类似于下面:

Name   Col1 Col2 Col3 Col4 Col5 Col6    
A      Y    Y         Y             
B      Y         Y    Y         Y
C           Y    Y          Y       
D      Y    

我想添加一个列来计算包含类似于以下值的其他列:

Name   Col1 Col2 Col3 Col4 Col5 Col6  Score
A      Y    Y         Y               3
B      Y         Y    Y         Y     4
C           Y    Y          Y         3
D      Y                              1

我已尝试以下但没有成功:

df['Score'] = df.count(df[['Col1','Col2','Col3','Col4','Col5','Col6']], axis='columns')
python pandas
2个回答
1
投票

如果存在缺失值,请使用

DataFrame.count
和列子集:

df['Score'] = df[['Col1','Col2','Col3','Col4','Col5','Col6']].count(axis=1)

0
投票

假设空单元格是

''
,您可以使用:

df['Score'] = df[['Col1','Col2','Col3','Col4','Col5','Col6']].ne('').sum(axis=1)

或者:

df['Score'] = df[['Col1','Col2','Col3','Col4','Col5','Col6']].eq('Y').sum(axis=1)

输出:

  Name Col1 Col2 Col3 Col4 Col5 Col6  Count
0    A    Y    Y         Y                3
1    B    Y         Y    Y         Y      4
2    C         Y    Y         Y           3
3    D    Y                               1
© www.soinside.com 2019 - 2024. All rights reserved.