Dictionary where list is value as dataframe

It might not be the right way to use dataframes, but I have a dictionary where the values ​​are a list of items. For example:

my_dict = {'a':[1,2,3], 'b':[3,4,5]}

      

I want to create a dataframe where indices are keys and there is one column where value is a list. This is the result I would like to see:

In [69]: my_df
Out[69]: 
              0
a     [1, 2, 3]
b  [3, 4, 5, 6]

      

This is the closest I got by changing the dictionary value to a list of lists and using transpose. What's the best way?

In [64]: my_dict = {'a':[[1,2,3]], 'b':[[3,4,5,6]]}

In [65]: my_df = pd.DataFrame(my_dict)

In [66]: print my_df
           a             b
0  [1, 2, 3]  [3, 4, 5, 6]

In [67]: my_df.T
Out[67]: 
              0
a     [1, 2, 3]
b  [3, 4, 5, 6]

      

Thanks for the help!

+3


source to share


1 answer


import pandas as pd

my_dict = {'a':[1,2,3], 'b':[3,4,5]}

pd.DataFrame([[i] for i in my_dict.values()],index=my_dict)
Out[3]: 
           0
a  [1, 2, 3]
b  [3, 4, 5]

      

But since you have more Series

than a DataFrame

:

pd.Series(my_dict)
Out[4]: 
a    [1, 2, 3]
b    [3, 4, 5]

      



and if you need you can convert it to DataFrame

:

pd.DataFrame(pd.Series(my_dict))
Out[5]: 
           0
a  [1, 2, 3]
b  [3, 4, 5]

      

+3


source







All Articles