Home > other >  Dictionary of different value types into pandas df
Dictionary of different value types into pandas df

Time:06-04

I have a dictionary mapped out as:

{
   "TopKey":{
      "Key1":"Dictionary",
      "Key2":"String",
      "Key3":None,
      "Key4":"String"
   }
}

And would like to map this out as as a pandas dataframe as

TopKey Value
Key1 Dictionary
Key2 String
Key3 None
Key4 String

I've been looking into documentation and the closest I've found was being able to do something like:

pd.DataFrame(dict["TopKey"]).T.reset_index().rename(columns={"index": "TopKey"}).transpose()

But that explodes the df into a 4 by 4 matrix. Is this due to resetting the index which is causing the dictionary to explode the records out?

CodePudding user response:

pd.DataFrame(sitevar).reset_index().rename(columns={"index": "TopKey", "TopKey": "Value"})

Output:

  TopKey       Value
0   Key1  Dictionary
1   Key2      String
2   Key3        None
3   Key4      String

CodePudding user response:

There is not direct "one-shot" way to my knowledge, here is another approach:

key = 'TopKey'
pd.Series(sitevar[key]).rename_axis(key).to_frame('Value').reset_index()
# or
# pd.Series(sitevar[key], name='Value').rename_axis(key).to_frame().reset_index()

output:

  TopKey       Value
0   Key1  Dictionary
1   Key2      String
2   Key3        None
3   Key4      String

CodePudding user response:

pandas.DataFrame.from_dict(data)
  • Related