gpt4 book ai didi

python - 如何在数据框中搜索列表中的项目并对它们进行计数

转载 作者:行者123 更新时间:2023-12-04 15:29:48 25 4
gpt4 key购买 nike

我有以下数据框及其输出。

import pandas as pd
animal = ["monkey"] + ["tiger"] + ["bat"]
valores = [1] + [2] + [3]
dframe = pd.DataFrame({"animal": animal, "valor": valores})

数据框:

    animal  valor
0 monkey 1
1 tiger 2
2 bat 3

我有一个列表,我想在数据框中逐项搜索,如果匹配则创建一个带有计数器的新列,单词可以是大写或小写,并且总和相同。

other_list = ['monkey', 'tiger', 'Tiger','tiger','Monkey']

animal valor count
0 monkey 1 2
1 tiger 2 3
2 bat 3 0

谢谢。

最佳答案

第一部分,我会选择@Dani,但将计数器转换为系列:

from collections import Counter
counts = pd.Series(Counter(map(str.lower, other_list)), name='counts')

将此添加到数据框的第二部分,我将使用 appendjoin 来避免循环:

dframe = dframe.set_index('animal').join(counts).reset_index()
dframe['counts'] = dframe.counts.fillna(0).astype(int)

关于python - 如何在数据框中搜索列表中的项目并对它们进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452561/

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