如何复制numpy数组中的行或列?

Equ*_*Dev 4 python numpy python-3.x

拥有这个numpy数组:

[[0 1 2]
 [3 4 5]
 [6 7 8]] 
Run Code Online (Sandbox Code Playgroud)

我如何复制例如第1行,所以我得到以下内容?:

[[0 1 2]
 [3 4 5]
 [3 4 5]
 [6 7 8]] 
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 9

方法#1

一种方法np.insert-

np.insert(a,2,a[1],axis=0)
Run Code Online (Sandbox Code Playgroud)

对于复制列,请使用它axis=1-

np.insert(a,2,a[:,1],axis=1)
Run Code Online (Sandbox Code Playgroud)

将函数作为具有通用重复次数的函数 -

def dup_rows(a, indx, num_dups=1):
    return np.insert(a,[indx+1]*num_dups,a[indx],axis=0)

def dup_cols(a, indx, num_dups=1):
    return np.insert(a,[indx+1]*num_dups,a[:,[indx]],axis=1)
Run Code Online (Sandbox Code Playgroud)

样品运行 -

In [82]: a
Out[82]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [83]: np.insert(a,2,a[1],axis=0)
Out[83]: 
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])

In [141]: np.insert(a,2,a[:,1],axis=1)
Out[141]: 
array([[0, 1, 1, 2],
       [3, 4, 4, 5],
       [6, 7, 7, 8]])
Run Code Online (Sandbox Code Playgroud)

通用案例运行 -

In [255]: a
Out[255]: 
array([[19, 65, 87, 46, 85],
       [18, 45, 90, 26, 31],
       [49, 35, 34, 62, 24],
       [47, 85, 63, 91, 33],
       [54, 37, 89, 79, 50],
       [53, 54, 66, 59, 38]])

In [256]: dup_rows(a, indx=4, num_dups=3)
Out[256]: 
array([[19, 65, 87, 46, 85],
       [18, 45, 90, 26, 31],
       [49, 35, 34, 62, 24],
       [47, 85, 63, 91, 33],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [53, 54, 66, 59, 38]])

In [253]: dup_cols(a, indx=2, num_dups=2)
Out[253]: 
array([[19, 65, 87, 87, 87, 46, 85],
       [18, 45, 90, 90, 90, 26, 31],
       [49, 35, 34, 34, 34, 62, 24],
       [47, 85, 63, 63, 63, 91, 33],
       [54, 37, 89, 89, 89, 79, 50],
       [53, 54, 66, 66, 66, 59, 38]])
Run Code Online (Sandbox Code Playgroud)

方法#2

另一个np.repeat-

In [102]: reps = np.ones(a.shape[0],dtype=int)

In [103]: reps[1] = 2 # duplication factor

In [104]: np.repeat(a,reps,axis=0)
Out[104]: 
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])
Run Code Online (Sandbox Code Playgroud)


Mos*_*oye 7

通过对指数进行过采样

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>>
>>> a[[0,1,1,2]]
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])
Run Code Online (Sandbox Code Playgroud)