简体   繁体   中英

Looping over a python list of tuples and applying a function

I have a data frame in this format:

  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]]

Each row is trajectory data, and I have to find distance between the trajectories with a function func_dist , like this:

 x = df.iloc[0]["points"].tolist() 
 y = df.iloc[3]["points"].tolist()
 func_dist(x, y)

I have a list l of indices for trajectories of interest..

l = [0,1,3]

I must find the distance between all the possible pairs of trajectories; in the case above, this is 0-1, 0-3, and 1-3. I know how to generate a list of pairs using

 pairsets = list(itertools.combinations(l, 2)) 

which returns

 [(0,1), (0,3), (1,3)]

Since the list may have over 100 indices, I am trying to automate this process and store the distances calculated between each pair in a new_df data frame.

I tried the following code for distance computation:

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) 

But it calculates only the last pair, 1-3. How to calculate all of the pairs and create a new data frame like this:

  traj1       traj2       distance
  0           1           some_val
  0           3           some_val
  1           3           some_val

This is simply a matter of handling your indices properly. For each pair, you grab the two indices, assign your data sets, and compute the distance.

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] )

You can combine the first two lines:

for i, j in pairsets:

The dist_table gives you a 2D list that you should be able to convert to a new data frame with a simple PANDAS call.

Does that get you moving?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM