I have a dictionary like this:
{1: ["a", "b", "c"],
2: ["d", "e", "f", "g"]}
that I want to turn into a dataframe like this:
| id | item |
|---|---|
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | d |
| 2 | e |
| 2 | f |
| 2 | g |
but when I try use pandas.DataFrame.from_dict() I get an error because my arrays aren’t the same length. How can I accomplish what I’m trying to do here?
>Solution :
Example
data = {1: ["a", "b", "c"],
2: ["d", "e", "f", "g"]}
Code
pd.Series(data).explode()
output(series):
1 a
1 b
1 c
2 d
2 e
2 f
2 g
dtype: object
if you want result to dataframe, use following code:
pd.Series(data).explode().reset_index().set_axis(['id', 'item'], axis=1)
output(dataframe):
id item
0 1 a
1 1 b
2 1 c
3 2 d
4 2 e
5 2 f
6 2 g