gpt4 book ai didi

python - 计算存储在列表中的值出现的行数

转载 作者:行者123 更新时间:2023-12-04 07:59:47 25 4
gpt4 key购买 nike

有一个数据帧 df将数据保存在字符串列表中:

>> df
words
0 [a,b,c]
1 [a]
2 [x,c,c]
3 [a]
...
我想计算 words 中每个值的行数发生在。例如:
a: 3
b: 1
c: 2
x: 1
我使用以下方法获取 DataFrame 中所有唯一单词的列表:
>> from collections import OrderedDict #using OrderedDict to keep word order
>> l = []
>> df.words.apply(lambda x: l.append(x)) #add list of words to a list
>> l = list(OrderedDict.fromkeys([j for i in l for j in i])) #merge list of lists and remove duplicates
>> print(l)
[a,b,c,x]
我从这里开始查看列表 l并检查 df 的每一行如果单词存在,则对每个单词求和 Bool 值。
data = []
for w in l:
tmp = []
df.words.apply(lambda x: tmp.append(w in x))
data.append(sum(tmp))
然后我可以创建一个单词字典和它们的数量。然而,这是非常低效的,因为它需要很长时间(70,000 多个字和 50,000 多行)。有没有更快的方法来做到这一点?

最佳答案

您可以使用 Series.explode Series.value_counts

df['words'].explode().values_counts(sort=False)
另一种选择是使用 itertools.chain.from_iterable collections.Counter
counts = Counter(chain.from_iterable(df['words']))
pd.Series(counts)
a 3
b 1
c 3
x 1
dtype: int64

关于python - 计算存储在列表中的值出现的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66531405/

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