我創建了以下函式來從引數創建資料框
gamle_dfs = []
def create_lines_df_2(Origin, Destination, line_, nodes_):
dict_ = [{'Origin':Origin,'Destination':Destination,'geometry':line_,
'length':line_.length,
'osmid':[nodes_.index.values]}]
df = gpd.GeoDataFrame(dict_, geometry='geometry',
crs=oslo_edges_proj.crs).reset_index()
gamle_dfs.append(df)
我將準確地使用這個函式 289 次來為每個地區路線有 17 個資料幀 1,但該函式回傳每個資料幀作為串列的一個元素,我希望它們作為一個資料幀,如果我將串列更改為 GeoDataframe,它將給我一個空的資料框,
結果是這樣的:
[ Origin Destination geometry \
0 Gamle Oslo Grünerl?kka LINESTRING (599408.712 6642638.038, 599353.853...
length osmid
0 1960.743326 [[1485390119, 79624, 1485390291, 24935363, 345... ,
Origin Destination geometry \
0 Gamle Oslo Sagene LINESTRING (599408.712 6642638.038, 599353.853...
length osmid
0 3799.280637 [[1485390119, 79624, 1485390291, 24935363, 345... ]
我可以使用 gamle_dfs[0,.,.,n] 訪問每個資料幀
將輸出作為函式附加的資料幀的解決方案是什么?
編輯添加示例:
origin = ['a']
destinations = ['b','c','d','e']
line1 = ['shaprely.geometry.nodes from a to b']
line2 = ['shaprely.geometry.nodes from a to c']
line3 = ['shaprely.geometry.nodes from a to d']
line4 = ['shaprely.geometry.nodes from a to e']
gamle_dfs = []
def create_lines_df_2test(Origin, Destination, line_):
dict_ =
[{'Origin':Origin,'Destination':Destination,'geometry':line_,
'length':len(line_)}]
df = pd.DataFrame(dict_)
gamle_dfs.append(df)
當我只需要從那些 gamle_dfs 索引中組合 1 個時,這給了我一個資料幀串列
uj5u.com熱心網友回復:
如果您確實需要在回圈中生成資料幀,我會修改函式以輸出資料幀,而不是更新全域變數。然后我會pandas.concat用來生成最終的資料幀:
def create_lines_df_2test(Origin, Destination, line_):
dict_ = [{'Origin':Origin,'Destination':Destination,'geometry':line_,
'length':len(line_)}]
df = pd.DataFrame(dict_)
return df
lines = (line1, line2, line3, line4)
pd.concat([create_lines_df_2test(origin, destinations, l) for l in lines])
如果從一開始就擁有所有資料,只需直接生成資料幀:
df = pd.DataFrame({'Origin': [origin for x in range(len(lines))],
'Destination': [destinations for x in range(len(lines))],
'geometry': lines,
'length': map(len, lines),
})
輸出:
Origin Destination geometry length
0 [a] [b, c, d, e] [shaprely.geometry.nodes from a to b] 1
1 [a] [b, c, d, e] [shaprely.geometry.nodes from a to c] 1
2 [a] [b, c, d, e] [shaprely.geometry.nodes from a to d] 1
3 [a] [b, c, d, e] [shaprely.geometry.nodes from a to e] 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400751.html
