Lan*_*anc 4 python numpy scipy
有谁知道如何在矩阵中逐行获取唯一元素。例如输入矩阵可能类似于:
a = [[1,2,1,3,4,1,3],
[5,5,3,1,5,1,2],
[1,2,3,4,5,6,7],
[9,3,8,2,9,8,4],
[4,6,7,4,2,3,5]]
Run Code Online (Sandbox Code Playgroud)
它应该返回以下内容:
b = rowWiseUnique(a)
=> b = [[1,2,3,4,0,0,0],
[5,3,1,2,0,0,0],
[1,2,3,4,5,6,7],
[9,3,8,2,4,0,0],
[4,6,7,2,3,5,0]]
Run Code Online (Sandbox Code Playgroud)
在 numpy 中执行此操作最有效的方法是什么?我尝试了以下代码,是否有更好、更短的方法来执行此操作?
import numpy as np
def uniqueRowElements(row):
length = row.shape[0]
newRow = np.unique(row)
zerosNumb = length-newRow.shape[0]
zeros = np.zeros(zerosNumb)
nR = np.concatenate((newRow,zeros),axis=0)
return nR
b = map(uniqueRowElements,a)
b = np.asarray(b)
print b
Run Code Online (Sandbox Code Playgroud)
假设中的值a是浮点数,您可以使用:
def using_complex(a):
weight = 1j*np.linspace(0, a.shape[1], a.shape[0], endpoint=False)
b = a + weight[:, np.newaxis]
u, ind = np.unique(b, return_index=True)
b = np.zeros_like(a)
np.put(b, ind, a.flat[ind])
return b
In [46]: using_complex(a)
Out[46]:
array([[1, 2, 0, 3, 4, 0, 0],
[5, 0, 3, 1, 0, 0, 2],
[1, 2, 3, 4, 5, 6, 7],
[9, 3, 8, 2, 0, 0, 4],
[4, 6, 7, 0, 2, 3, 5]])
Run Code Online (Sandbox Code Playgroud)
请注意,using_complex不会以与 ; 相同的顺序返回唯一值rowWiseUnique。根据问题下面的评论,不需要对值进行排序。
最有效的方法可能取决于数组中的行数。如果行数不太大,那么使用map或 afor-loop单独处理每一行的方法是很好的,但如果行数很多,您可以通过使用 numpy 技巧通过一次调用 np.array 来处理整个数组来做得更好。独特的。
诀窍是为每一行添加一个唯一的虚数。这样,当您调用 时np.unique,原始数组中的浮点数如果出现在不同行中,将被识别为不同的值,但如果它们出现在同一行中,则被视为相同的值。
下面,这个技巧在函数中实现using_complex。rowWiseUnique以下是将原始方法 与using_complex和进行比较的基准solve:
In [87]: arr = np.random.randint(10, size=(100000, 10))
In [88]: %timeit rowWiseUnique(arr)
1 loops, best of 3: 1.34 s per loop
In [89]: %timeit solve(arr)
1 loops, best of 3: 1.78 s per loop
In [90]: %timeit using_complex(arr)
1 loops, best of 3: 206 ms per loop
Run Code Online (Sandbox Code Playgroud)
import numpy as np
a = np.array([[1,2,1,3,4,1,3],
[5,5,3,1,5,1,2],
[1,2,3,4,5,6,7],
[9,3,8,2,9,8,4],
[4,6,7,4,2,3,5]])
def using_complex(a):
weight = 1j*np.linspace(0, a.shape[1], a.shape[0], endpoint=False)
b = a + weight[:, np.newaxis]
u, ind = np.unique(b, return_index=True)
b = np.zeros_like(a)
np.put(b, ind, a.flat[ind])
return b
def rowWiseUnique(a):
b = map(uniqueRowElements,a)
b = np.asarray(b)
return b
def uniqueRowElements(row):
length = row.shape[0]
newRow = np.unique(row)
zerosNumb = length-newRow.shape[0]
zeros = np.zeros(zerosNumb)
nR = np.concatenate((newRow,zeros),axis=0)
return nR
def solve(arr):
n = arr.shape[1]
new_arr = np.empty(arr.shape)
for i, row in enumerate(arr):
new_row = np.unique(row)
new_arr[i] = np.hstack((new_row, np.zeros(n - len(new_row))))
return new_arr
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5147 次 |
| 最近记录: |