Reputation: 121
I have a dictionary of connected components of a graph, for example:
d = {'A':[1,5,7],'B':[2,4], 'C':[3,6]}
and I want to create a dataframe of the form:
cc node
0 A 1
1 A 5
2 A 7
3 B 2
4 B 4
5 C 3
6 C 6
I can do this by creating a df for each key in the dictionary and then connecting them, but I am looking for a better solution.
Upvotes: 0
Views: 74
Reputation: 30940
IIUC,
cc, node = [], []
for key, value in d.items():
cc += [key] * len(value)
node += value
df = pd.DataFrame({'cc' : cc, 'node' : node})
print(df)
Output
cc node
0 A 1
1 A 5
2 A 7
3 B 2
4 B 4
5 C 3
Upvotes: 1
Reputation: 2302
Maybe something like this:
import pandas as pd
d = {'A':[1,5,7],'B':[2,4], 'C':[3,6]}
temp = [[key, n] for key, val in d.items() for n in val]
df = pd.DataFrame(df, columns=['cc', 'node'])
print(df)
Output:
cc node
0 A 1
1 A 5
2 A 7
3 B 2
4 B 4
5 C 3
6 C 6
Upvotes: 1
Reputation: 1055
d = {'A':[1,5,7],'B':[2,4], 'C':[3,6]}
df = []
for k,v in d.items():
for i in v:
df.append([k,i])
for l in df:
print(l)
['A', 1]
['A', 5]
['A', 7]
['B', 2]
['B', 4]
['C', 3]
['C', 6]
Upvotes: 1