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

标签 python pandas

我正在尝试计算 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/

相关文章:

python - 使用 Python 多处理进行通信时 OSX 和 Linux 之间的性能差异

python - 从哪里获得/如何构建支持 python 3.0 的 mod_wsgi 的 Windows 二进制文件?

python - 如何添加包含预测的新列?

python - Pandas 数据框删除常量列

python - 如何使用 Plotly 绘制循环的局部变量

python - 在 python : difference between two lists

python - ImportError:无法从 'scan_videos' 导入名称 'subliminal'

python - 使用groupby函数时如何将元素粘合到列表中?

python - 使用列的 MultiIndex 将高 DataFrame 转换为宽格式

python - OpenAI GPT-3 API : How to parse the response into an ordered list or dictionary?