【问题标题】:Pandas: Looking to avoid a for loop when creating a nested dictionaryPandas:希望在创建嵌套字典时避免 for 循环
【发布时间】:2022-01-19 17:14:05
【问题描述】:

这是我的数据:

df:

id sub_id
A  1
A  2
B  3
B  4

我有以下数组:

[[1,2],
[2,5],
[1,4],
[7,8]]

这是我的代码:

from collections import defaultdict

sub_id_array_dict = defaultdict(dict)
for i, s, a in zip(df['id'].to_list(), df['sub_id'].to_list(), arrays):
    sub_id_array_dict[i][s] = a

现在,我的实际数据框总共包含 1 亿行(唯一 sub_id)和 50 万个唯一 ID。理想情况下,我想避免 for 循环。

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    假设 arrays 变量的行数与 Dataframe 中的行数相同,

    df['value'] = arrays
    

    通过分组转换成字典

    df.groupby('id').apply(lambda x: dict(zip(x.sub_id, x.value))).to_dict()
    

    输出

    {'A': {1: [1, 2], 2: [2, 5]}, 'B': {3: [1, 4], 4: [7, 8]}}
    

    【讨论】:

      【解决方案2】:

      您可以将arrays 分配给一列,然后使用pivot

      df['value'] = arrays
      out = df.pivot('sub_id','id','value').to_dict()
      

      输出:

      {'A': {1: [1, 2], 2: [2, 5], 3: nan, 4: nan},
       'B': {1: nan, 2: nan, 3: [1, 4], 4: [7, 8]}}
      

      如果你想摆脱NaNs:

      new_out = {key: {k:v for k,v in val.items() if v is not np.nan} for key, val in out.items()}
      

      输出:

      {'A': {1: [1, 2], 2: [2, 5]}, 'B': {3: [1, 4], 4: [7, 8]}}
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2012-06-25
        • 2017-08-27
        • 2017-11-11
        • 2020-11-02
        • 2021-07-25
        • 2019-03-29
        • 2022-01-03
        • 2021-08-19
        相关资源
        最近更新 更多