1

Let's say, I have a dictionary like below

sample_dict= { 'A':[[1,2,3],[4,5,6]],
               'B':[[7,8,9],[10,11,12]],
               'C':[[13,14,15]]}

I would like to convert this dictionary to dataframe like below.

Expected Output:

|----------------|-------------|------------|----------|
|      keys      |     col1    |    col2    |   col3   |
|----------------|-------------|------------|----------|
|       A        |      1      |      2     |     3    |
|----------------|-------------|------------|----------|
|       A        |      4      |      5     |     6    |
|----------------|-------------|------------|----------|
|       B        |      7      |      8     |     9    |
|----------------|-------------|------------|----------|
|       B        |      10     |      11    |     12   |
|----------------|-------------|------------|----------|
|       c        |      13     |      14    |     15   |
|----------------|-------------|------------|----------|

while performing this below code

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

I'm getting the resultant output as:

|----------------|-------------|--------------|
|                |     0       |    1         |
|----------------|-------------|--------------|
|       A        |   [1,2,3]   |   [4,5,6]    |
|----------------|-------------|--------------|
|       B        |   [7,8,9]   |  [10,11,12]  |
|----------------|-------------|--------------|
|       C        | [13,14,15]  |     None     |
|----------------|-------------|--------------|

Ideas are welcome!!

Thanks in Advance!!

2 Answers2

1

Do:

import pandas as pd

sample_dict = {'A': [[1, 2, 3], [4, 5, 6]],
               'B': [[7, 8, 9], [10, 11, 12]],
               'C': [[13, 14, 15]]}


df = pd.DataFrame([[k, *v] for k, vs in sample_dict.items() for v in vs], columns=["keys", "c1", "c2", "c3"])
print(df)

Output

  keys  c1  c2  c3
0    A   1   2   3
1    A   4   5   6
2    B   7   8   9
3    B  10  11  12
4    C  13  14  15

If the number of columns is not known before hand, do:

df = pd.DataFrame([[k, *v] for k, vs in sample_dict.items() for v in vs]) \
    .rename(columns=lambda x: "c" + str(x)) \
    .rename(columns={"c0": "keys"})
print(df)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

This will do what you want from stackoverflow question Look at accepted awnser

df=pd.DataFrame.from_dict(sample_dict,orient='index').reset_index
Vahalaru
  • 380
  • 4
  • 15
  • This code makes my keys as index and getting different columns for each list of values for that specific key...and answer provided by dani was helpful for my problem...Really appreciated for your effort!..Thanks a lot. – kamalesh waran Nov 19 '20 at 19:45