How to convert the dictionary to dataframe in this format?

Viewed 99

I have a dictionary

dic = {'a': ['b', 'c', 'd'], 'x': ['y', 'z', 'w']}

Then I would like to convert df of the form

enter image description here

This conversion is repeated many times. Could you please elaborate on an efficient way to do so?

4 Answers

use melt

d = {'a': ['b', 'c', 'd'], 'x': ['y', 'z', 'w']}
df = pd.DataFrame(d).melt(var_name='root',value_name='node')

print(df)

  root node
0    a    b
1    a    c
2    a    d
3    x    y
4    x    z
5    x    w

You can melt it:

dic = {'a': ['b', 'c', 'd'], 'x': ['y', 'z', 'w']}
df = pd.DataFrame(dic)
df.melt(value_name='node', var_name='root')
    root node
0   a    b
1   a    c
2   a    d
3   x    y
4   x    z
5   x    w

Edit: To handle uneven node lengths, create the original df explicitly from_dict with index orientation, which will pad the uneven nodes as None. Then dropna at the end:

dic = {'a': ['b', 'c', 'd'], 'x': ['y', 'z', 'w', 't']}
df = pd.DataFrame.from_dict(dic, orient='index').T
df.melt(value_name='node', var_name='root').dropna()
    root node
0   a    b
1   a    c
2   a    d
4   x    y
5   x    z
6   x    w
7   x    t

You should iterate over your dict and create the data that your want.

import pandas as pd


dic = {'a': ['b', 'c', 'd'], 'x': ['y', 'z', 'w']}

column = ('node', 'root')
data = [(node, root) for root, nodes in dic.items() for node in nodes]

d = pd.DataFrame(columns=column, data=data)

print(d)

Output:

  node root
0    b    a
1    c    a
2    d    a
3    y    x
4    z    x
5    w    x

df = pd.DataFrame.from_dict(dic)
df.to_csv('test.csv', index=False) 

you're giving the data frame a .csv extension, and naming it test.csv

Related