gpt4 book ai didi

python - 获取 pandas 列表列中元素频率的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:53 26 4
gpt4 key购买 nike

我正在尝试计算 pandas DataFrame 的列中元素的频率。

一些玩具数据:

d = pd.DataFrame({'letters':[['a', 'b', 'c'], np.nan, ['a', 'e', 'd', 'c'], ['a', 'e', 'c']]})

我能想到的是遍历行并将值添加到字典中:

letter_count = {}
for i in range(len(d)):
if d.iloc[i, ]['letters'] is np.nan:
continue
else:
for letter in d.iloc[i, ]['letters']:
letter_count[letter] = letter_count.get(letter, 0) + 1

这对我有用,只是速度不是很快,因为我的数据集很大。我假设通过避免显式 for 循环可能会有所帮助,但我无法想出更“ Pandas ”的方式来做到这一点。

感谢任何帮助。

最佳答案

使用chain.from_iterable 将列表展平,然后使用Counter 对其进行计数:

from itertools import chain
from collections import Counter

pd.Series(Counter(chain.from_iterable(d.letters.dropna())))

a 3
b 1
c 3
e 2
d 1
dtype: int64

或者,使用 value_counts 作为计数步骤:

pd.Series(list(chain.from_iterable(d.letters.dropna()))).value_counts()

a 3
c 3
e 2
b 1
d 1
dtype: int64

或者,np.unique,也非常高效:

u, c = np.unique(list(chain.from_iterable(d.letters.dropna())), return_counts=True)

pd.Series(dict(zip(u, c)))

a 3
b 1
c 3
d 1
e 2
dtype: int64

关于python - 获取 pandas 列表列中元素频率的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54114809/

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