0

Given the following data:

d = {"a": {1.0: "this", 2.0: "that"}, "b": {1.0: "here", 2.0: "there"}}

How would one create dataframe:

  var  code   name
0   a   1.0   this
1   a   2.0   that
2   b   1.0   here
3   b   2.0  there

2 Answers 2

3

I suggest use nested list comprehension for list of tuples and pass to DataFrame constructor:

L = [(k, k1, v1) for k, v in d.items() for k1, v1 in v.items()]
df = pd.DataFrame(L, columns=['var', 'code', 'name'])
print (df)
  var  code   name
0   a   1.0   this
1   a   2.0   that
2   b   1.0   here
3   b   2.0  there

Alternative solution with DataFrame constructor, DataFrame.rename_axis, reshape by DataFrame.unstack and Series.reset_index:

df = (pd.DataFrame(d)
        .rename_axis(index='code', columns='var')
        .unstack()
        .reset_index(name='name'))
print (df)
  var  code   name
0   a   1.0   this
1   a   2.0   that
2   b   1.0   here
3   b   2.0  there
Sign up to request clarification or add additional context in comments.

1 Comment

Yess... A little trickier to generate a more representative input being a dict
2

We can construct a dataframe from the dictionary, stack and reset_index:

df = pd.DataFrame(d).stack()
df.index =  df.index.set_names(['var', 'code'])
df.reset_index(name='name')

print(df)

   var code   name
0  1.0    a   this
1  1.0    b   here
2  2.0    a   that
3  2.0    b  there

2 Comments

thanks - this is nice but seems to be dependent on the values being 1,2?
Not really @baxx Stacking will create a multiindex, and by resetting the inedx var will just be set to whatever key the dictionary has. So IIUC it should be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.