Reputation: 1692
Let's say that I have a dictionary that looks something like this:
{'blue': [1,2,3], 'red' : [1,3]}
I would like to transform this into a dataframe of two columns in which one column is the color name (red or blue) and the other is the value. Perhaps, something like this:
blue 1
blue 2
blue 3
red 1
red 3
Is there a short way in doing so? I have checked ways of transferring dictionaries into dataframe but none of them talked about the case in which values are lists.
Thanks.
Upvotes: 0
Views: 40
Reputation: 2533
Maybe the easiest way would be to transform your dict into the list of tuples before giving it to pd.DataFrame
import pandas as pd
d = {'blue': [1,2,3], 'red' : [1,3]}
lst = [(k, i) for k, v in d.items() for i in v]
df = pd.DataFrame(lst)
df
0 1
0 blue 1
1 blue 2
2 blue 3
3 red 1
4 red 3
Upvotes: 2
Reputation: 13255
Use pandas.concat
with pandas.Series
:
d = {'blue': [1,2,3], 'red' : [1,3]}
s = pd.concat([pd.Series(v, index=np.repeat(k, len(v))) for k,v in d.items()])
print(s)
blue 1
blue 2
blue 3
red 1
red 3
dtype: int64
Upvotes: 1