【问题标题】:How to combine multiple lists of tuples from dataframe into one dictionary?如何将数据帧中的多个元组列表组合到一个字典中?
【发布时间】:2020-12-17 08:50:44
【问题描述】:

我环顾四周,无法真正将我找到的不同部分解决方案中的信息片段放在一起,所以问题出在:

在分析亚马逊评论时,我将数据组织到一个数据框中,并创建了一个列,其中包含每条评论中使用的每个单词的计数。所以我有一列,其中每一行都包含一个元组列表。

我正在寻找一种有效的方法(我的数据集包含数百万条评论)将所有这些元组列表合并到一个字典中。理想情况下,这本词典应该已经包含了每个单词的权重(即他们各自评论的投票数),不过如果问得太多,我以后可以弄清楚。

这是一个例子:

df['words'] = [('thank', 2),('you',2),('this',5)],
              [('interesting',1),('this',3)],
              [('thank,3),('me',2),('later',2)],
              [('me',2),('interesting',1)],
              [('thank',2),('you',1),('again',1)]
df['votes'] = 10
               5
               2
               1
               1

所需的输出(或嵌套字典) - 第一个数字是出现在元组中的频率总和,而第二个数字是权重总和,位于“投票”列中:

top_words = {'this':(8,15),'thank':(7,13),'me':(4,3),'you':(3,11),'interesting':(2,6),'later':(2,2),'again':(1,1)}

我尝试过 dict(zip(*df[words]) 和其他一些类似的方法,但总是出错(添加的加权信息很棒,但还不是绝对必要的)。我感觉答案是相当简单,但它在逃避我。

建议?

【问题讨论】:

  • 发布示例数据框

标签: python list dataframe dictionary tuples


【解决方案1】:

您可以为此使用 reduce 函数和 numpy。

df = {}
df['words'] = [[('thank', 2),('you',2),('this',5)],
              [('interesting',1),('this',3)],
              [('thank',3),('me',2),('later',2)],
              [('me',2),('interesting',1)],
              [('thank',2),('you',1),('again',1)]]
df['votes'] = [10,5,2,1,1]

from functools import reduce
import numpy as np

data = dict(zip(df['votes'], df['words']))
'''
{
 1: [('thank', 2), ('you', 1), ('again', 1)],
 2: [('thank', 3), ('me', 2), ('later', 2)],
 5: [('interesting', 1), ('this', 3)],
 10: [('thank', 2), ('you', 2), ('this', 5)]
}
'''

def add(a, x, data):
  for word in data[x]:
    if word[0] not in list(a.keys()):
      a[word[0]] = (0, 0)
    a[word[0]] = tuple(np.add(a[word[0]], (word[1], x)))
  return a

output = reduce(lambda a, x: add(a, x, data), data, {})

'''
{
 'again': (1, 1),
 'interesting': (1, 5),
 'later': (2, 2),
 'me': (2, 2),
 'thank': (7, 13),
 'this': (8, 15),
 'you': (3, 11)
}
'''

我使用了dict(zip(df['votes'], df['words'])),因为reduce函数需要输入与输出的类型相同。

【讨论】:

    【解决方案2】:

    试试看:

    import numpy as np
    
    top_words = {}
    for ind, row in df.iterrows():
        for word in row["words"]:
            top_words[word[0]] = (sum(j[1] for i in df["words"]  for j in i if j[0] == word[0]), 
                                  sum(i["votes"] for ind, i in df.iterrows() if word[0] in np.array(i["words"])))
    

    【讨论】:

    • 看起来不错,但会引发元素比较错误。不太清楚为什么。
    猜你喜欢
    • 2019-07-03
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2018-06-16
    • 2019-05-27
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多