denpy
denpy

Reputation: 279

Convert Dictionary into Dataframe

I am trying to convert a dictionary into a dataframe.

import pandas as pd
dict = {'A': [1,2,3], 'B': [1,2,3,4])
pd.DataFrame.from_dict(dict, orient = 'index').T  

Expect:

    A        B
0   [1,2,3]  [1,2,3,4]

But got instead:

   A      B
-----------
0  1      a
1  2      b
2  3      c
3  None   d

Upvotes: 3

Views: 71

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195603

Try to put the dictionary inside list ([]):

import pandas as pd

dct = {"A": [1, 2, 3], "B": [1, 2, 3, 4]}

df = pd.DataFrame([dct])
print(df)

Prints:

           A             B
0  [1, 2, 3]  [1, 2, 3, 4]

Note: Don't use reserved words such as dict for variable names.

Upvotes: 4

Related Questions