加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:41:54 所属栏目:Python 来源:网络整理
导读:我在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 b0 {'dried': 1,'oak': 2} 21 {'fruity':

我在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}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读