4

Is there a built-in function apart from DataFrame.from_dict able to create a dataframe from a dictionary with unequal list of values?

What I am trying to do create a dataframe from the following dictionary:

d = {'g': {1, 2, 3}, 'h': {4, 5}}

so the output should look like:

   value  class
0    1        g
1    2        g
2    3        g
3    4        h
4    5        h

Is having the set instead of a list a problem?

rafaelc
  • 57,686
  • 15
  • 58
  • 82

3 Answers3

7

Yet another way using melt

pd.DataFrame(d.values(), d.keys()).T.melt().dropna()
rafaelc
  • 57,686
  • 15
  • 58
  • 82
4

If you don't mind manually unwrapping, you can achieve this through

In [9]: pd.DataFrame([(x, k) for k, v in d.items() for x in v], columns=['value', 'class'])
Out[9]:
   value class
0      1     g
1      2     g
2      3     g
3      4     h
4      5     h
fuglede
  • 17,388
  • 2
  • 54
  • 99
0

I am using unnesting

unnesting(pd.Series(d).apply(list).to_frame('name'),['name']).reset_index()
  index  name
0     g     1
1     g     2
2     g     3
3     h     4
4     h     5
BENY
  • 317,841
  • 20
  • 164
  • 234