【问题标题】:How to find sum of dictionaries in a pandas DataFrame across all rows?如何在所有行的 pandas DataFrame 中查找字典的总和?
【发布时间】:2018-10-17 12:44:15
【问题描述】:

我有一个数据框

df = pd.DataFrame({'keywords': [{'a': 3, 'b': 4, 'c': 5}, {'c':1, 'd':2}, {'a':5, 'c':21, 'd':4}, {'b':2, 'c':1, 'g':1, 'h':1, 'i':1}]})

我想在不使用iterrows的情况下在所有行中添加所有元素:

a: 8
b: 6
c: 28
d: 6
g: 1
h: 1
i: 1

注意:在原始 DataFrame 的单行中没有元素出现两次。

【问题讨论】:

    标签: python pandas counter


    【解决方案1】:

    使用collections.Counter,您可以sum 一个可迭代的Counter 对象。由于Counterdict 的子类,因此您可以提供给pd.DataFrame.from_dict

    from collections import Counter
    
    counts = sum(map(Counter, df['keywords']), Counter())
    res = pd.DataFrame.from_dict(counts, orient='index')
    
    print(res)
    
        0
    a   8
    b   6
    c  28
    d   6
    g   1
    h   1
    i   1
    

    【讨论】:

    • 认为我可以通过收藏来做到这一点,但不知道该怎么做。谢谢!
    • 有没有更节省内存的方法呢?我的数据框很大,需要很长时间。
    • @panaceanoob,我已更新为 map(Counter, df['keywords'])。从这里看不到太大的改进。您已经/选择了一个内存效率非常低的起点(在数据框中保存字典)。不建议这样做。 sum + map 是懒惰的,内存不是瓶颈,不是它需要很长时间的原因。
    【解决方案2】:

    不确定这与@jpp 的答案在优化方面的比较如何,但我会试一试。

    # What we're starting out with
    df = pd.DataFrame({'keywords': [{'a': 3, 'b': 4, 'c': 5}, {'c':1, 'd':2}, {'a':5, 'c':21, 'd':4}, {'b':2, 'c':1, 'g':1, 'h':1, 'i':1}]})
    
    # Turns the array of dictionaries into a DataFrame
    values_df = pd.DataFrame(df["keywords"].values.tolist())
    
    # Sums up the individual keys
    sums = {key:values_df[key].sum() for key in values_df.columns}
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      相关资源
      最近更新 更多