Create dataframe pandas 1 key and some non-standard values in the dictionary

Asked

Viewed 31 times

0

I have a dictionary in Python:

dict = {0:[['tela1'],['tela2'],['tela3']], 1:[['tela2']], 2:[['tela5'],['tela7']], 4:[['tela1'],['tela3']]}

and would like to transform into a dataframe as follows:

Id Values
0 tela1
0 tela2
0 tela3
1 tela2
2 tela5
2 tela7
4 tela1
4 tela3
  • Put what you tried to do into the question. Hug!

1 answer

0

import pandas as pd

dicionario = {0:[['tela1'],['tela2'],['tela3']], 
              1:[['tela2']], 
              2:[['tela5'],['tela7']], 
              4:[['tela1'],['tela3']]}

df = pd.DataFrame.from_dict(dicionario, orient='index')
df = df.T.melt().dropna()
df = df.rename(columns={'variable':'id','value':'Valores'})
df = df.explode('Valores')
id Values
0 tela1
0 tela2
0 tela3
1 tela2
2 tela5
2 tela7
4 tela1
4 tela3

One of the possible solutions using pandas from Dict.

The melt is used to turn columns into rows. explode serves to remove items from within a list and create a new record.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.