[英]How to effectively unpack this type of structure and create a DataFrame?
在使用生成x和y坐標時
import networkx as nx
nx.fruchterman_reingold_layout()
我剩下這種類型的數據結構:
{'SomeKey': array([value1, value2]),
'SomeOtherKey': array([value1, value2])}
我已經嘗試過以下代碼:
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)
我收到一個錯誤,說我為標量值或空的DataFrame提供了錯誤的索引:
Empty DataFrame
Columns: [Person, x, y]
Index: []
嘗試不同的方法也是無效的:
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]]})
根據您的數據:
pd.DataFrame.from_dict
應該可以解壓縮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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.