计算datafram所有行的列表中单词的出现次数

2024-05-08 00:32:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,其中一列的行包含值列表。我想统计一下列表中所有单词在所有行中出现的次数。在

例如:数据帧df

Column A         Column B
animal            [cat, dog, tiger]
place             [italy, china, japan]
pets              [cat, dog]

那么我需要的结果是:

^{pr2}$

Tags: 数据dataframedf列表placecolumn单词次数
2条回答

您需要将值展平到简单的列表和计数值-按^{}或按^{}

from collections import Counter

s = pd.Series(Counter([y for x in df['Column B'] for y in x]))
print (s)
cat      2
dog      2
tiger    1
italy    1
china    1
japan    1
dtype: int64

备选方案1:

^{pr2}$

备选方案2:

s = pd.Series(np.concatenate(df['Column B'])).value_counts()

大数据中的慢替代:

s = pd.Series(df['Column B'].sum()).value_counts()

使用集合中的计数器并打印值。请检查以下代码以供参考。在

import pandas as pd

#for counting the elements
from collections import Counter

#dataframe with list values in column B
df = pd.DataFrame([[1,['apple','mango','apple'],3],[1,['mango','mango','soni'],3]],columns=['A','B','C'])

#formatting the output post counting
for i,row in df.iterrows():
    c = Counter(row['B'])
    print(f'for index {i}')
    for k in c.keys():
        print(f'{k}: {c.get(k)}')

相关问题 更多 >