Home > Software design >  how to transform a dict of lists to a dataframe in python?
how to transform a dict of lists to a dataframe in python?

Time:12-06

I have a dict in python like this:

d = {"a": [1,2,3], "b": [4,5,6]}

I want to transform in a dataframe like this:

letter number
a 1
a 2
a 3
b 4
b 5
b 6

i have tried this code:

df = pd.DataFrame.from_dict(vulnerabilidade, orient = 'index').T

but this gave me:

a 1
2 3
b 4
5 6

CodePudding user response:

You can always read your data in as you already have and then .melt it:

When passed no id_vars or value_vars, melt turns each of your columns into their own rows.

import pandas as pd

d = {"a": [1,2,3], "b": [4,5,6]}
out = pd.DataFrame(d).melt(var_name='letter', value_name='value')

print(out)
  letter  value
0      a      1
1      a      2
2      a      3
3      b      4
4      b      5
5      b      6

CodePudding user response:

To use 'letter' and 'number' as column labels you could use:

a2 = [[key, val] for key, x in d.items() for val in x]
dict2 = pd.DataFrame(a2, columns = ['letter', 'number'])

which gives

  letter  number
0      a       1
1      a       2
2      a       3
3      b       4
4      b       5
5      b       6

CodePudding user response:

This will yield what you want (there might be a simpler way though):

import pandas as pd
my_dict = {"a": [1,2,3], "b": [4,5,6]}

my_list = [[key, val] for key in my_dict for val in my_dict[key] ]
df = pd.DataFrame(my_list, columns=['letter','number'])

df
# Out[106]: 
#   letter  number
# 0      a       1
# 1      a       2
# 2      a       3
# 3      b       4
# 4      b       5
# 5      b       6

CodePudding user response:

Yet another possible solution:

(pd.Series(d, index=d.keys(), name='numbers')
 .rename_axis('letters').reset_index()
 .explode('numbers', ignore_index=True))

Output:

  letters numbers
0       a       1
1       a       2
2       a       3
3       b       4
4       b       5
5       b       6
  • Related