gpt4 book ai didi

python - 如何在 Pandas 中的列和列表之间创建具有计数的列?

转载 作者:行者123 更新时间:2023-12-04 09:03:46 26 4
gpt4 key购买 nike

我想创建一个专栏 df['score']返回单元格和列表之间共同值的计数。

输入:

correct_list = ['cats','dogs']
answer
0 cats, dogs, pigs
1 cats, dogs
2 dogs, pigs
3 cats
4 pigs

def animal_count(dataframe):
count = 0
for term in df['answer']:
if term in symptom_list:
df['score'] = count + 1

animal_count(df)


预期输出:
correct_list = ['cats','dogs']

answer score
0 cats, dogs, pigs 2
1 cats, dogs 2
2 dogs, pigs 1
3 cats 1
4 pigs 0


有任何想法吗?谢谢!

最佳答案

使用 Series.str.count 的另一种解决方案:

df['score'] = df['answer'].str.count('|'.join(correct_list))

[出去]
             answer  score
0 cats, dogs, pigs 2
1 cats, dogs 2
2 dogs, pigs 1
3 cats 1
4 pigs 0

更新

正如@PrinceFrancis 所指出的,如果 catsdogs不应该算作 2 ,然后您可以更改您的正则表达式模式以适应:
df = pd.DataFrame({'answer': ['cats, dogs, pigs', 'cats, dogs', 'dogs, pigs', 'cats', 'pigs', 'catsdogs']})

pat = '|'.join([fr'\b{x}\b' for x in correct_list])
df['score'] = df['answer'].str.count(pat)

[出去]
             answer  score
0 cats, dogs, pigs 2
1 cats, dogs 2
2 dogs, pigs 1
3 cats 1
4 pigs 0
5 catsdogs 0

关于python - 如何在 Pandas 中的列和列表之间创建具有计数的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59361181/

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