【问题标题】:Creating Dictionary from Pandas DataFrame Column Based on Unique Values in Column根据列中的唯一值从 Pandas DataFrame 列创建字典
【发布时间】:2018-08-25 01:02:03
【问题描述】:

我有一个令人头疼的问题,我不确定是否可以通过一两行代码来解决,我正在尝试。我或多或少可以在没有数据框的情况下做到这一点(例如,如果数据只是 .txt),但我想看看它是否可以用 pandas 完成。

下面是 df.head(10),我想创建一个字典,其中 keys 是解析后的唯一 day_of_week 数字(1-7,适用于周日至周六)和 values 是每个day_of_week 值上出现的births总和

    year    month   date_of_month   day_of_week births
  0 1994      1          1              6        8096
  1 1994      1          2              7        7772
  2 1994      1          3              1        10142
  3 1994      1          4              2        11248
  4 1994      1          5              3        11053
  5 1994      1          6              4        11406
  6 1994      1          7              5        11251
  7 1994      1          8              6        8653
  8 1994      1          9              7        7910
  9 1994      1          10             1        10498

我可以轻松地为各个 day_of_week 值创建 SUM:

df.groupby[df['day_of_week'] == 1, 'births'].sum()

它总结了day_of_week == 1 上发生的所有出生。我可以创建day_of_week 值的字典:

d = {i : 0 for i in df['day_of_week']}

产生字典,d:

{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}

但我无法将两者连接起来,因此我可以解析 day_of_week 数字,将这些数字分配给字典的 key,然后将每个 @987654335 上出现的 births 相加@,然后将这些总和值分配给它们各自的键。

如果有人有建议!我在下面创建了一个虚拟数据框,它可以复制条件,如果有帮助的话,因为day_of_week 值确实在我的数据框中重复(尽管您无法从df.head() 中分辨出来)。

d = {'day_of_week' : pd.Series([1, 6, 6, 5, 3, 2, 6, 4, 4, 7, 1]),
    'births' : pd.Series([5544, 23456, 473, 34885, 3498, 324, 6898, 83845, 959, 8923, 39577])}
df_dummy = pd.DataFrame(d)

【问题讨论】:

  • 抱歉,我的意思是写:df.groupby('day_of_week')['births'].sum()[1] 用于总结出现在 day_of_week == 1 上的所有 births 的代码

标签: python pandas numpy dictionary dataframe


【解决方案1】:

看来你需要

df_dummy.set_index('day_of_week').births.sum(level=0).to_dict()
Out[30]: {1: 45121, 2: 324, 3: 3498, 4: 84804, 5: 34885, 6: 30827, 7: 8923}

【讨论】:

  • @RichardS yw :-) 快乐编码
【解决方案2】:

这绝对可以用 pandas 一句话来回答。只需使用 groupby 构造对您解析的星期几进行分组,然后对出生人数求和。 Pandas 内置了将其转换为字典的功能,其中您的键是星期几,值是总和:

import pandas as pd
day_of_week = [6, 7, 1, 2, 3, 4, 5, 6, 7, 1]
births = [8096, 7772, 10142, 11248, 11053, 11406, 11251, 8653, 7910, 10498]

df = pd.DataFrame({'day_of_week': day_of_week,
               'births': births})

df.groupby('day_of_week')['births'].sum().to_dict()
# output: {1: 20640, 2: 11248, 3: 11053, 4: 11406, 5: 11251, 6: 16749, 7: 15682}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2021-06-20
    • 2019-04-17
    • 2020-08-31
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多