Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading