计算数据框所有行的列表中单词的出现

时间:2019-04-08 05:41:01

标签: python pandas

我有一个数据框,其中的一列包含带有值列表的行。我想计算所有行中列表内所有单词的出现次数。

例如:数据框df

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

然后我需要的结果是:

cat : 2
dog: 2
tiger: 1 and so on

2 个答案:

答案 0 :(得分:1)

您需要平整值以简化列表和计数值-通过CounterSeries.value_counts

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

Alternative1:

from itertools import chain
from collections import Counter

s = pd.Series(Counter(chain.from_iterable(df['Column B'])))

Alternative2:

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

大数据中的慢替代方案:

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

答案 1 :(得分:0)

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

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)}')