Reputation: 407
This may be an incorrect way to use dataframes, but I have a dictionary where the values are a list of items. Such as:
my_dict = {'a':[1,2,3], 'b':[3,4,5]}
I want to create a data frame where the indices are the keys and there is one column, where the value is the list. This is the output I'd like to see:
In [69]: my_df
Out[69]:
0
a [1, 2, 3]
b [3, 4, 5, 6]
This is the closest I've gotten, by changing the dictionary value to a list of lists and using a transpose. What is the better 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!
Upvotes: 3
Views: 1393
Reputation: 80346
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 as what you have is more of a Series
than a DataFrame
:
pd.Series(my_dict)
Out[4]:
a [1, 2, 3]
b [3, 4, 5]
and if you need to, you can convert it to a DataFrame
:
pd.DataFrame(pd.Series(my_dict))
Out[5]:
0
a [1, 2, 3]
b [3, 4, 5]
Upvotes: 3