【问题标题】:Extracting elements from list of dictionary in pandas从熊猫字典列表中提取元素
【发布时间】:2021-01-01 15:36:58
【问题描述】:

在数据框的一列中,我对数据框的每一行都有以下分数:

[{'score': 100, 'bonus': 10}, {'score': 60, 'bonus': 0}]
[{'score': 80, 'bonus': 20}, {'score': 90, 'bonus': 30}]

输出

输出将是两个新列,用于每行的分数变化和奖金变化。因此,第一行的 df.delta_score = -40 和 df.delta_bonus = -10,第二行的 df.delta_score = 10 和 df.delta_bonus = 10。

[{'score': 100, 'bonus': 10}, {'score': 60, 'bonus': 0}, -40, -10]
[{'score': 100, 'bonus': 10}, {'score': 60, 'bonus': 0}, 10, 10]

我想计算每个人(行)的分数和奖金的值变化,并使用结果值生成新列。我对这种数据类型很困惑,因为它似乎是一个字典列表,但由于每个字典都有相同的键,我想使用一个运算符来计算差异。任何帮助将不胜感激。

【问题讨论】:

  • 怎么知道红利差应该是10还是-10
  • 你的预期输出是什么,不是用文字,而是如果你能用数字显示你的预期?
  • 正如大卫所说 - 请在帖子中提供预期的输出。
  • 编辑以包含输出

标签: python pandas list dictionary multi-index


【解决方案1】:

我们将简单地创建两个新列BonusScore。您可以使用.get() 的列表推导根据键bonusscore 检索值。然后,通过订阅[1] 并减去[0],从第一个值中减去第二个值

import pandas as pd
df = pd.DataFrame({'dict_col': [[{'score': 100, 'bonus': 10}, {'score': 60, 'bonus': 0}],
                                [{'score': 80, 'bonus': 20}, {'score': 90, 'bonus': 30}]]})
df['Bonus'] = df['dict_col'].apply(lambda x: [d.get('bonus') for d in x][1] - [d.get('bonus') for d in x][0])
df['Score'] = df['dict_col'].apply(lambda x: [d.get('score') for d in x][1] - [d.get('score') for d in x][0])
df
Out[1]: 
                                            dict_col  Bonus  Score
0  [{'score': 100, 'bonus': 10}, {'score': 60, 'b...    -10    -40
1  [{'score': 80, 'bonus': 20}, {'score': 90, 'bo...     10     10

【讨论】:

    【解决方案2】:

    我们可以explode 然后我们得到数据帧

    s = df['Col'].explode()
    calcu = pd.DataFrame(s.tolist(), index=s.index)
    calcu
    Out[170]: 
       score  bonus
    0    100     10
    0     60      0
    1     80     20
    1     90     30
    

    在这之后你可以做

    calcu.groupby(level=0)...(calculation follow by groupby)
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 2019-05-18
      • 2022-01-23
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多