2

I have a dictionary in python, each key has a value of nested lists, like following:

test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3],[4,5,6]]}

and I want to convert the dictionary key into dataframe column names in pandas and the nested lists into series of list, like following:

'x' 'y'
[1,2,3] [1,2,3]
[4,5,6] [4,5,6]

Is there any way to do so?

3 Answers3

3

Try:

import pandas as pd
df = pd.DataFrame(test)
print(df)

Here is the output in my ide:

Output

If you want to save the Dataframe into a csv file, you should:

output_name = 'myfile.csv'
df.to_csv(output_name)

This will create a csv, universal name for excel like files into your working directory. You can check it's existence with:

import os
os.listdir()
Girolamo
  • 326
  • 3
  • 11
  • 2
    Clarification: this can be worked only because `x` and `y` have the same length. `pd.DataFrame({'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3]]})` raises `ValueError: All arrays must be of the same length` – Corralien Dec 23 '21 at 10:10
  • Correct, in case you need to create a dataframe where dictionary values do have different lenght, refer to: https://stackoverflow.com/a/19736406/15488129 – Girolamo Dec 23 '21 at 10:32
2

Just convert it to a dataframe, this code returns what you need.

import pandas as pd
import numpy as np

test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3],[4,5,6]]}
df = pd.DataFrame(test)

This returns the following:

           x          y
0  [1, 2, 3]  [1, 2, 3]
1  [4, 5, 6]  [4, 5, 6]

You can then convert it to a csv file and set the index=False to remove the row numbers(0 and 1 in this case):

df.to_csv('df.csv', index=False)

That should give you the output as follows:

 x          y
[1, 2, 3]  [1, 2, 3]
[4, 5, 6]  [4, 5, 6]
Tayyeb Ali
  • 45
  • 8
0

Try this :
pd.DataFrame(columns =test.keys() ,data = test.values())

It resolves the Value error thrown by @girolamo's answer .

For test = {'x':[[1,2,3],[4,5,6]], 'y':[[1,2,3]]}

It gives output : enter image description here

That is if len of x and y are different it returns None