Kaszanas
Kaszanas

Reputation: 475

How to effectively unpack this type of structure and create a DataFrame?

While generating x and y coordinates using

import networkx as nx
nx.fruchterman_reingold_layout()

I am left with this type of data structure:

{'SomeKey': array([value1,  value2]),
'SomeOtherKey': array([value1, value2])}

I have already tried code such as:

empty_dataframe = pd.DataFrame(columns=["Person", "x", "y"])

list_of_keys = list(fruchterman.keys())

for key in list_of_keys:
    dataframe = pd.DataFrame({"Person": key, "x": [fruchterman[key][0]], "y": [fruchterman[key][1]]})
    for_later_save.append(dataframe, ignore_index=True)

I am either getting an error that says that I provide wrong index for a scalar value or an empty DataFrame:

Empty DataFrame
Columns: [Person, x, y]
Index: []

Trying a different approach is also ineffective:

Exception has occurred: IndexError
invalid index to scalar variable.
  File "Y:\Directory1\Directory2\Directory3\calculations.py", line 75, in <module>
    dataframe = pd.DataFrame({"Person": key, "x": [fruchterman[key][0][0]], "y": [fruchterman[key][0][1]]})

Upvotes: 0

Views: 65

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62413

Given your data:

Data:

data = {'SomeKey': array(['value1',  'value2']),
        'SomeOtherKey': array(['value1', 'value2'])}

orient='columns':

df = pd.DataFrame.from_dict(data, orient='columns')
print(df)

  SomeKey SomeOtherKey
0  value1       value1
1  value2       value2

orient='index':

df = pd.DataFrame.from_dict(data, orient='index')
df.reset_index(inplace=True)
df.columns = ['Person', 'x', 'y']
print(df)

         Person       x       y
0       SomeKey  value1  value2
1  SomeOtherKey  value1  value2

Upvotes: 2

Related Questions