0

I want to form a pandas dataframe from a dictionary dictionary:

    dictionary = 
       {0: [1, 2, 3 ,4],
       1: [2, 4, 6, 7, 9, 10, ...],
       ...
       }

Values of dictionary are unequal lists.

I want to a form a dataframe out of this with keys as index and values as list.

Desired dataframe:

    df (keys are the index of df)=
      Index.  Column 1
       0       [1, 2, 3 ,4]
       1       [2, 4, 6, 7, 9, 10, ...]
       ...

I tried,

    df = pd.DataFrame.from_dict(dictionary, orient='index')

But, it just explodes the number of columns into maximum size of the list in one of the values of dictionary

How to achieve above by forming only one column?

learner
  • 857
  • 1
  • 14
  • 28
  • here's your answer: https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths – YOLO Aug 19 '20 at 15:56
  • @YOLO, I had a look at the question. The orientation desired in that question is different from mine. – learner Aug 19 '20 at 16:00
  • 1
    `pd.DataFrame.from_dict({k:[v] for k,v in d.items()},orient='index').reset_index()` wrap a list around each value – anky Aug 19 '20 at 16:03
  • 1
    It works. Thanks. It is even faster than the answer. – learner Aug 19 '20 at 16:12

1 Answers1

3

You can try:

f = pd.DataFrame({k: pd.Series([v]) for k,v in d.items()}).T.reset_index()
print(f)

   index                                                   0
0      0                                     [0, 1, 2, 3, 4]
1      1                      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2      2  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Sample Data

d = {0: list(range(5)), 1: list(range(10)), 2: list(range(15))}
YOLO
  • 20,181
  • 5
  • 20
  • 40
  • I see. I mean I wanted keys of the dictionary to become rows of the dataframe (index of the `df` ), which I feel like has been answered in the comment to my question by providing `orient=index` to `from_dict` method. – learner Aug 19 '20 at 16:18