gpt4 book ai didi

python - 比较数据框中的列以获得所需的输出

转载 作者:行者123 更新时间:2023-12-01 09:08:41 25 4
gpt4 key购买 nike

假设这是我的输入数据框:

Name  Death1  Return1   Death2  Return2
A Yes Yes NaN NaN
B No No Yes Yes
C Yes Yes Yes Yes
D NaN NaN NaN NaN

我想要计算一个角色死亡的次数并将其存储在一个新列中。

# My approach.
def clean_deaths(row):
num_deaths = 0
cols = ['Death1', 'Death2']
for c in cols:
death = row[c]
if pd.isnull(death) or death == 'NO':
continue
elif death == 'YES':
num_deaths += 1
return num_deaths

df['Deaths'] = df.apply(clean_deaths, axis=1)

我对自己的方法并不满意。我希望看到其他方法来实现这一目标。

output: 
Name Death1 Return1 Death2 Return2 Deaths
A Yes Yes NaN NaN 1
B No No Yes Yes 1
C Yes Yes Yes Yes 2
D NaN NaN NaN NaN 0

最佳答案

我认为需要按名称或 filter 过滤列,比较eq (==) 和每行最后的 sum True 值:

df['Deaths'] = df[['Death1', 'Death2']].eq('Yes').sum(axis=1)
print (df)
Name Death1 Return1 Death2 Return2 Deaths
0 A Yes Yes NaN NaN 1
1 B No No Yes Yes 1
2 C Yes Yes Yes Yes 2
3 D NaN NaN NaN NaN 0
<小时/>
df['Deaths'] = df.filter(like='Death').eq('Yes').sum(axis=1)

详细信息:

print (df[['Death1', 'Death2']].eq('Yes'))
Death1 Death2
0 True False
1 False True
2 True True
3 False False

关于python - 比较数据框中的列以获得所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com