有时将行向量或列向量“克隆”到矩阵中是有用的。克隆的意思是转换行向量,比如

[1, 2, 3]

变成一个矩阵

[[1, 2, 3],
 [1, 2, 3],
 [1, 2, 3]]

或者一个列向量,比如

[[1],
 [2],
 [3]]

into

[[1, 1, 1]
 [2, 2, 2]
 [3, 3, 3]]

在MATLAB或八度音阶中,这很容易做到:

 x = [1, 2, 3]
 a = ones(3, 1) * x
 a =

    1   2   3
    1   2   3
    1   2   3
    
 b = (x') * ones(1, 3)
 b =

    1   1   1
    2   2   2
    3   3   3

我想在numpy中重复这一点,但不成功

In [14]: x = array([1, 2, 3])
In [14]: ones((3, 1)) * x
Out[14]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])
# so far so good
In [16]: x.transpose() * ones((1, 3))
Out[16]: array([[ 1.,  2.,  3.]])
# DAMN
# I end up with 
In [17]: (ones((3, 1)) * x).transpose()
Out[17]:
array([[ 1.,  1.,  1.],
       [ 2.,  2.,  2.],
       [ 3.,  3.,  3.]])

为什么第一种方法(在[16])不工作?有没有一种更优雅的方法在python中实现这个任务?


当前回答

如果你有一个pandas数据框架,并且想要保存dtypes,甚至是分类,这是一个快速的方法:

import numpy as np
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
number_repeats = 50
new_df = df.reindex(np.tile(df.index, number_repeats))

其他回答

如果你有一个pandas数据框架,并且想要保存dtypes,甚至是分类,这是一个快速的方法:

import numpy as np
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
number_repeats = 50
new_df = df.reindex(np.tile(df.index, number_repeats))

你可以使用

np.tile(x,3).reshape((4,3))

Tile将生成向量的代表

重塑会给你想要的形状

回到最初的问题

在MATLAB或八度音阶中,这很容易做到: X = [1,2,3] A = ones(3,1) * x ...

在numpy中,这几乎是一样的(也很容易记住):

x = [1, 2, 3]
a = np.tile(x, (3, 1))

另一个解决方案

>> x = np.array([1,2,3])
>> y = x[None, :] * np.ones((3,))[:, None]
>> y
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])

为什么?当然,重复和平铺是正确的方法。但是None索引是一个强大的工具,它可以让我多次快速向量化操作(尽管它很快就会非常消耗内存!)

下面是我自己代码中的一个例子:

# trajectory is a sequence of xy coordinates [n_points, 2]
# xy_obstacles is a list of obstacles' xy coordinates [n_obstacles, 2]
# to compute dx, dy distance between every obstacle and every pose in the trajectory
deltas = trajectory[:, None, :2] - xy_obstacles[None, :, :2]
# we can easily convert x-y distance to a norm
distances = np.linalg.norm(deltas, axis=-1)
# distances is now [timesteps, obstacles]. Now we can for example find the closest obstacle at every point in the trajectory by doing
closest_obstacles = np.argmin(distances, axis=1)
# we could also find how safe the trajectory is, by finding the smallest distance over the entire trajectory
danger = np.min(distances)

使用numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

或者对于重复列:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])