【问题标题】:How to make a nested Dictionary from a Pandas data frame suing several columns?如何使用多列从 Pandas 数据框制作嵌套字典?
【发布时间】:2022-01-10 04:05:50
【问题描述】:

我正在尝试从 pandas 数据框创建一个嵌套字典。

我有这个数据框:

     id1            ids1                         Name1        Name2      ids2                     ID     col1  Goal     col2    col3       
0   85643        234,34,11223,345,345_2         aasd1        vaasd1    2234,354,223,35,3435     G-0001     1   NaN       3       1      
1   85644        2343,355,121,34                aasd2                                           G-0002     2   56.0000   4       22     
2   8564312      24 , 23 ,244 ,2421 ,567 ,789   aabsd1                                          G-00023    3   NaN       32      33     
3   8564314      87 ,35 ,67_1                   aabsd2       averabsd   387 ,355 ,667_1         G-01034    4   89.0000   43      44 

df.to_dict()
#Here is wht you requested
{'id1  ': {0: 85643, 1: 85644, 2: 8564312, 3: 8564314},
 'ids1 ': {0: '234,34,11223,345,345_2      ',
  1: '2343,355,121,34             ',
  2: '24 , 23 ,244 ,2421 ,567 ,789',
  3: '87 ,35 ,67_1                '},
 'Name1': {0: 'aasd1 ', 1: 'aasd2 ', 2: 'aabsd1', 3: 'aabsd2'},
 'Name2': {0: 'vaasd1  ', 1: '        ', 2: '        ', 3: 'averabsd'},
 'ids2': {0: '2234,354,223,35,3435',
  1: '                    ',
  2: '                    ',
  3: ' 387 ,355 ,667_1  '},
 'ID': {0: 'G-0001 ', 1: 'G-0002 ', 2: 'G-00023', 3: 'G-01034'},
 'col1': {0: 1, 1: 2, 2: 3, 3: 4},
 'Goal    ': {0: ' NaN    ', 1: 56, 2: ' NaN    ', 3: 89},
 'col2': {0: 3, 1: 4, 2: 32, 3: 43},
 'col3': {0: 1, 1: 22, 2: 33, 3: 44}}

“ID”列中的每一行都必须是键。在该字典中,“Name1”列和“Name2”列需要作为列表存在。 “Name1”列列表与“ids1”列关联,“Name2”列列表与“ids2”列关联。 我还需要将“ID”列名也放入该列表中。

所以我想在下面创建一个嵌套字典。

mapper={
"G-0001":{"aasd1":['G-0001','234','34','11223','345','345_2'],
"vaasd1":['G-0001','2234','354','223','35','3435']},
"G-0002":{"aasd2":['G-0002','2343','355','121','34']},
"G-00023":{"aabsd1":['G-00023','24' , '23' ,'244' ,'2421' ,'567' ,'789']},
"G-01034":{"aabsd2":['G-01034','87' ,'35' ,'67_1'],
"averabsd":['G-01034','387' ,'355' ,'667_1']}
}

可以创建吗? 有人可以给我一个想法吗? 任何事情都值得赞赏。提前致谢!

【问题讨论】:

  • 您能提供您的df 作为代码吗?即df.to_dict()
  • 如果这个 dict 看起来是个好主意,你接下来要做什么?您正在将易于操作的数据更改为数据结构,委婉地说,不方便。
  • 我编辑了代码并包含了 df.to_dict()

标签: python pandas dictionary


【解决方案1】:

试试:

  1. 将 DataFrame 从宽格式转换为长格式
  2. 删除没有“名称”的行并将“ID”附加到“ID”
  3. groupby 并构造所需的输出字典。
#remove extra spaces from column names
df.columns = df.columns.str.strip()

#assign and index and convert DataFrame from wide to long format
df["idx"] = df.index
wtl = pd.wide_to_long(df, ["Name","ids"], "idx","j")

#drop rows without Name
wtl = wtl[wtl["Name"].str.strip().str.len().gt(0)]

#append ID and clean up the ids column
wtl["ids"] = wtl["ID"]+","+wtl["ids"]
wtl["ids"] = wtl["ids"] = wtl["ids"].str.split("\s?,\s?")

#groupby and construct required dictionary
output = wtl.groupby("ID").apply(lambda x: dict(zip(x["Name"],x["ids"]))).to_dict()

>>> output
{'G-0001': {'aasd1': ['G-0001', '234', '34', '11223', '345', '345_2'],
            'vaasd1': ['G-0001', '2234', '354', '223', '35', '3435']},
 'G-0002': {'aasd2': ['G-0002', '2343', '355', '121', '34']},
 'G-00023': {'aabsd1': ['G-00023', '24', '23', '244', '2421', '567', '789']},
 'G-01034': {'aabsd2': ['G-01034', '87', '35', '67_1'],
             'averabsd': ['G-01034', '387', '355', '667_1']}}

【讨论】:

  • 理解你所做的事情有点复杂(我的意思是如何使用 wtl = pd.wide_to_long(df, ["Name","ids"], "idx" 获取 Name1 和 Name2 列"j"))。但是,它可以按我的需要工作。谢谢,真的很感激!很棒的工作!
  • 通读wide_to_long的官方文档
  • 正确输出仅适用于 Name2。我的看起来像这样。 {'G-0001': {'aasd1': nan, 'vaasd1': ['G-0001', '2234', '354', '223', '35', '3435']}, 'G- 0002': {'aasd2': nan}, 'G-00023': {'aabsd1': nan}, 'G-01034': {'aabsd2': nan, 'averabsd': ['G-01034', ' 387','355','667_1']}}
  • @rra - 您需要更正列名。检查我的答案中新添加的顶行(使用strip)。
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2021-12-08
  • 2021-12-06
  • 2020-03-31
  • 1970-01-01
  • 2021-09-22
相关资源
最近更新 更多