【问题标题】:Creating new pandas dataframe after performing complex function执行复杂功能后创建新的熊猫数据框
【发布时间】:2017-06-02 00:18:02
【问题描述】:

我在以下df中有轨迹数据:

   vid        points
0   0        [[2,4], [5,6], [8,9]]
1   1        [[10,11], [12,13], [14,15]]
2   2        [[1,2], [3,4], [8,1]]
3   3        [[21,10], [8,8], [4,3]]
4   4        [[15,2], [16,1], [17,3]]

每个轨迹都是一个列表点,由 vid 标识。

我有一个函数,它计算两条轨迹之间的距离,让这个距离函数为 method_dist(x, y) ; x,y 是两条轨迹。

这是该方法的工作原理:

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

method_dist(x, y)

现在,method_dist 将计算索引 0 和索引 3(不是 vid)处的轨迹之间的距离。

由于我的 df 中有 100 行,如果可能的话,我想自动化这个过程。

如果我给出一个索引列表 [0, 1, 3], 我想创建一个函数或循环,在其中计算索引 0 和索引 1 处的轨迹之间的距离;然后是索引 0 和 3,然后是 1 和 3;直到计算出每对之间的距离,我想将 dist 存储在 df2 中,如下所示:

注意我们不是计算任意点之间的距离,“points”下的每个单元格是一个完整的轨迹,函数method_dist是计算整个轨迹之间的距离。

     traj1_idx       traj2_idx        distance
  0    0             1                some_val
  1    0             3                some_val
  2    1             3                some_val

或者,即使我必须手动计算一对之间的距离,我也想创建一个新的 df,每次我采用两条轨迹时,它至少会在新的 df 中添加计算的距离和轨迹对。

请让我知道如何获得预期结果或者我是否需要更改任何内容。

谢谢

【问题讨论】:

  • 我正在做一些有趣的事情
  • 谢谢你,希望我有你的大脑。

标签: python pandas numpy dataframe


【解决方案1】:

创建一个自定义class,在其中将减法定义为method_dist

def method_dist(x, y):
    return abs(x - y)

class Trajectory(object):
    def __init__(self, a):
        self.data = np.asarray(a)

    def __sub__(self, other):
        return method_dist(self.data, other.data)

    def __repr__(self):
        return '☺ {}'.format(self.data.shape)

然后创建一系列这些东西

s = df.points.apply(Trajectory)
s

0    ☺ (3, 2)
1    ☺ (3, 2)
2    ☺ (3, 2)
3    ☺ (3, 2)
4    ☺ (3, 2)
Name: points, dtype: object

定义一个方便的函数来自动化不同的差异组合

def get_combo_diffs(a, idx):
    """`a` is an array of Trajectory objects.  The return
    statement shows a slice of `a` minus another slice of `a`.
    numpy will execute the underlying objects __sub__ method
    for each pair and return an array of the results."""

    # this bit just finds all combinations of 2 at a time from `idx`
    idx = np.asarray(idx)
    n = idx.size
    i, j = np.triu_indices(n, 1)

    return a[idx[i]] - a[idx[j]]

那就用吧……

get_combo_diffs(s.values, [0, 1, 3])

array([array([[8, 7],
       [7, 7],
       [6, 6]]),
       array([[19,  6],
       [ 3,  2],
       [ 4,  6]]),
       array([[11,  1],
       [ 4,  5],
       [10, 12]])], dtype=object)

第一个元素

get_combo_diffs(s.values, [0, 1, 3])

array([[8, 7], [7, 7], [6, 6]])

是两者的结果

first = np.array([[2, 4], [5, 6], [8, 9]])
second = np.array([[10, 11], [12, 13], [14, 15]])

method_dist(first, second)

array([[8, 7],
       [7, 7],
       [6, 6]])

或者等价

x, y = s.loc[0], s.loc[1]
x - y

array([[8, 7],
       [7, 7],
       [6, 6]])

【讨论】:

  • 我不确定代码在做什么,您是否考虑单行中每对点之间的距离?
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2016-08-28
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多