如何使用.apply()将一列词典合并为一个词典?

我在pandas数据框中有一列词典.

srs_tf = pd.Series([{'dried': 1,'oak': 2},{'fruity': 2,'earthy': 2},{'tones': 2,'oak': 4}]) 
srs_b = pd.Series([2,4,6]) 
df = pd.DataFrame({'tf': srs_tf,'b': srs_b}) 

df

                           tf  b
0      {'dried': 1,'oak': 2}  2
1  {'fruity': 2,'earthy': 2}  4
2      {'tones': 2,'oak': 4}  6

这些词典代表了葡萄酒描述中的词频(输入字典:{‘savoury’:1,’dried’:3,’thyme’:1,’notes’..}).我需要从这一列字典中创建一个输出字典,其中包含来自输​​入字典的所有键,并将它们映射到存在这些键的输入字典的数量.例如,单词“ dried”是输入字典中的850键,因此在输出字典{..’dried’:850 …}中.

我想尝试使用数据框.apply()方法,但是我认为使用不正确.

def worddict(row,description_counter):
    for key in row['tf'].keys():
        if key in description_counter.keys():
            description_counter[key] += 1
        else:
            description_counter[key] = 1
    return description_counter

description_counter = {}

output_dict = df_wine_list.apply(lambda x: worddict(x,description_counter),axis = 1)

有几件事.我认为我的轴应= 0而不是1,但是尝试时会出现此错误:KeyError:(‘tf’,’出现在未命名的索引:0′)

当我确实使用axis = 1时,我的函数将返回一列具有相同字典的字典,而不是单个字典.

最佳答案
您可以使用链和计数器:

from collections import Counter
from itertools import chain

Counter(chain.from_iterable(df['a']))
# Counter({'dried': 1,'earthy': 1,'fruity': 1,'oak': 2,'tones': 1})

要么,

Counter(y for x in df['a'] for y in x)
# Counter({'dried': 1,'tones': 1})

您还可以使用Index.value_counts,

pd.concat(map(pd.Series,df['a'])).index.value_counts().to_dict()
# {'dried': 1,'tones': 1}

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...