[英]Looping over a python list of tuples and applying a function
我有這種格式的數據框:
vid points
0 1 [[0,1], [0,2, [0,3]]
1 2 [[1,2], [1,4], [1,9], [1,7]]
2 3 [[2,1], [2,3], [2,8]]
3 4 [[3,2], [3,4], [3,5],[3,6]]
每行都是軌跡數據,我必須使用func_dist
函數查找軌跡之間的距離,如下所示:
x = df.iloc[0]["points"].tolist()
y = df.iloc[3]["points"].tolist()
func_dist(x, y)
我有興趣軌跡的索引列表l
..
l = [0,1,3]
我必須找到所有可能的軌跡對之間的距離; 在上述情況下,它是0-1、0-3和1-3。 我知道如何使用
pairsets = list(itertools.combinations(l, 2))
哪個返回
[(0,1), (0,3), (1,3)]
由於該列表可能有100多個索引,因此我試圖使此過程自動化,並將每對之間計算出的距離存儲在new_df
數據幀中。
我嘗試了以下代碼進行距離計算:
for pair in pairsets:
a, b = [m[0] for m in pairssets], [n[1] for n in pairsets]
for i in a:
x = df.iloc[i]["points"].tolist()
for j in b:
y = df.iloc[j]["points"].tolist()
dist = func_dist(x, y)
但是它只計算最后一對1-3。 如何計算所有對,並創建一個新的數據框,如下所示:
traj1 traj2 distance
0 1 some_val
0 3 some_val
1 3 some_val
這僅僅是正確處理索引的問題。 對於每一對,您都抓住兩個索引,分配數據集,然后計算距離。
dist_table = []
for pair in pairsets:
i, j = pair
x = df.iloc[i]["points"].tolist()
y = df.iloc[j]["points"].tolist()
dist = func_dist(x, y)
dist_table.append( [i, j, dist] )
您可以合並前兩行:
for i, j in pairsets:
dist_table
提供了一個二維列表,您應該可以通過一個簡單的PANDAS調用將其轉換為新的數據框。
那會讓你動起來嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.