【问题标题】:Pandas DataFrame nested dictionary (key+list(key:value))Pandas DataFrame 嵌套字典 (key+list(key:value))
【发布时间】:2020-11-24 18:27:34
【问题描述】:

数据框:

Main    1      2     3

key1    ins    tbr    a
key1    inb    tba    b
key1    inr    tbe    c

我有这个数据框,其中 1,2,3 是列,并且 Main 设置为索引 (set_index) 有没有办法告诉熊猫字典转换我需要嵌套字典。 IE。对于每个 Key 1 row-wise 都有一个值列表,在该值列表内有一个字典,其中列 (1,2,3)-> 也是键。这一切,一个一个,一行一行。 期望的输出:

key1:{1: 'ins', 2: 'tbr', 3: 'a'}
key1:{1: 'inb', 2: 'tba',3:'b'}
key1:{1: 'inr', 2: 'tbe', 3: 'c'}
key2:{....}
key2:{....}
etc

可重现的数据框:

df = pd.DataFrame(columns = ["Main_keys", "1", "2","3"])   
df['1'] = ['ins','inb','inr']
df['2']= ['tbr','tba','tbe]
df['3']= ['a','b','c']


dataf.set_index('Main_keys', inplace = True) 

这种伪代码方法不走运。

  • 我也尝试使用 zip() 似乎没有将字典列表连接到带有键的列的列

import pandas as pd

new_df = pd.DataFrame()
for elements_of_keys, list_of_dict in zip(col1, df_list):
    new_df[elements_of_keys] = list_of_dict  
 

一旦我将其转换为:

df = df.to_dict(orient='records')

我非常接近答案,但是我不知道如何解决或告诉熊猫我需要带有一堆键的附加列 (key1,key1,key1,key2,key2) -> 以及它的相应信息

最终需要的 json 输出:

{​​​​​​​ "key1":[{​​​​​​​ "1": "ins", "2": "tbr", "3": "a", }​​​​​​​], {​​​​​​​ "key1":[{​​​​​​​ "1": "inb", "2": "tba", "3": "b", }​​​​​​​, { "key1":[{​​​​​​​ "1": "inr", "2": "tbe", "3": "c" }​​​​​​​] }​​​​​​​] }​​​​​​​

【问题讨论】:

  • 请提供minimal reproducible example,以及当前和预期的输出。
  • 您知道字典中不能有重复的键,不是吗?
  • @QuangHoang Hoang 感谢您的回答,当然,这不是我要问的。如果您查看我刚刚添加的代码,一旦将数据框转换为字典(orient='index'),我会得到一个列表(在该列表中它是一个字典),因此,可以将字典列表连接到迭代键。
  • 你的意思是df.to_dict(orient='records')
  • @QuangHoang Hoang 正确,我的错误。这是我用过的

标签: python pandas dataframe


【解决方案1】:

您可以手动添加列:

out = pd.DataFrame({'Main':df.index, 'values': df.to_dict(orient='records')})

输出:

   Main                              values
0  key1  {'1': 'ins', '2': 'tbr', '3': 'a'}
1  key1  {'1': 'inb', '2': 'tba', '3': 'b'}
2  key1  {'1': 'inr', '2': 'tbe', '3': 'c'}

或者您的意思是将键添加为索引:

df.apply(pd.Series.to_dict, axis=1)

输出:

Main
key1    {'1': 'ins', '2': 'tbr', '3': 'a'}
key1    {'1': 'inb', '2': 'tba', '3': 'b'}
key1    {'1': 'inr', '2': 'tbe', '3': 'c'}
dtype: object

【讨论】:

  • 感谢您提供的解决方案很有意义。然而,理想情况下,它应该是一个列表,其中 1,2,3(初始列)也是键。
  • 你的意思是{k:v.to_dict(orient='records') for k, v in df.groupby(level=0)}
  • 我最终需要在json中得到的格式是:{​​​​​​​“key1”:[{​​​​​​​“1”:“ins”,“2 ": "tbr", "3": "a", }​​​​​​​​], {​​​​​​​“key1”:[{​​​​​​​“1”:“ inb”,“2”:“tba”,“3”:“b”,}​​​​​​​​,{“key1”:[{​​​​​​​“1”:“inr”, “2”:“tbe”,“3”:“c” }​​​​​​​​] }​​​​​​​​] }​​​​​​​​​​
  • 你应该在你的问题中指定:-)
  • @Ecko 您发布的内容不是有效的 JSON 对象。试试list(df.apply(lambda x: {x.name:x.to_dict()}, axis=1))
【解决方案2】:

df.set_index('Main', inplace=True) df = df.to_dict(orient = 'records')

这回答了问题,但并不完全。

但是,使用此代码,不明白为什么所有 'key1' 都消失了,不应该只是代替索引,仍然是个谜。

再次为没有提供可能更好地描述问题的 json 输出表示歉意

json 中的输出应该是这样的:

{​​​​​​​“key1”:[{​​​​​​​“1”:“ins”,“2”:“tbr”,“3”:“a”,}​ ​​​​​​], {​​​​​​​“key1”:[{​​​​​​​“1”:“inb”,“2”:“tba”,“3”:“b”,}​​​​ ​​​],{“key1”:[{​​​​​​​“1”:“inr”,“2”:“tbe”,“3”:“c”}​​​​​​​​ ] }​​​​​​​​] }

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2022-01-02
    • 1970-01-01
    • 2020-02-18
    • 2017-12-26
    • 2019-12-01
    • 2015-08-03
    • 2019-11-16
    • 2019-07-26
    相关资源
    最近更新 更多