Home > Enterprise >  Convert from dictionary to dataframe when arrays aren't equal length?
Convert from dictionary to dataframe when arrays aren't equal length?

Time:11-20

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?

CodePudding user response:

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

CodePudding user response:

    pd.concat([pd.DataFrame(v,index=[i]*len(v),columns=['items']) for i,v in map1.items()])\
      .rename_axis('id').reset_index()
    
      id items
    0   1     a
    1   1     b
    2   1     c
    3   2     d
    4   2     e
    5   2     f
    6   2     g
  • Related