Programing

Numpy-배열에 행 추가

lottogame 2020. 6. 20. 10:42
반응형

Numpy-배열에 행 추가


numpy 배열에 행을 어떻게 추가합니까?

배열 A가 있습니다.

A = array([[0, 1, 2], [0, 2, 0]])

X의 각 행의 첫 번째 요소가 특정 조건을 충족하면 다른 배열 X 에서이 배열에 행을 추가하고 싶습니다.

Numpy 배열에는 목록과 같은 'append'메서드가 없으므로 그렇게 보입니다.

A와 X가 목록이라면 나는 단지 다음과 같이 할 것입니다.

for i in X:
    if i[0] < 3:
        A.append(i)

동등한 것을 할 수 있는 수많은 방법이 있습니까?

고마워, S ;-)


무엇입니까 X? 2D 배열 인 경우 행을 숫자와 어떻게 비교할 수 i < 3있습니까?

OP의 의견 후 편집 :

A = array([[0, 1, 2], [0, 2, 0]])
X = array([[0, 1, 2], [1, 2, 0], [2, 1, 2], [3, 2, 0]])

첫 번째 요소의 A모든 행에 추가하십시오 .X< 3

A = vstack((A, X[X[:,0] < 3]))

# returns: 
array([[0, 1, 2],
       [0, 2, 0],
       [0, 1, 2],
       [1, 2, 0],
       [2, 1, 2]])

잘 당신은 이것을 할 수 있습니다 :

  newrow = [1,2,3]
  A = numpy.vstack([A, newrow])

이 질문은 7 년 전에 사용되었으므로 사용중인 최신 버전은 numpy 버전 1.13이며 python3은 행렬에 행을 추가하는 것과 동일한 일 을하고 있습니다. 두 번째 인수 에는 이중 괄호넣어야합니다 . 그렇지 않으면 치수 오류가 발생합니다.

여기에 행렬 A를 추가하고 있습니다

1 2 3
4 5 6

행으로

7 8 9

동일한 사용법 np.r_

A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)

    >> array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
#or 
np.r_[A,[[7,8,9]]]

열을 추가하고 싶은 경우 다른 사람에게만

array = np.c_[A,np.zeros(#A's row size)]

행렬 A에서 이전에 한 일을 따라 열을 추가

np.c_[A, [2,8]]

>> array([[1, 2, 3, 2],
          [4, 5, 6, 8]])

당신은 또한 이것을 할 수 있습니다 :

newrow = [1,2,3]
A = numpy.concatenate((A,newrow))

매 행마다 계산이 필요하지 않으면 파이썬에서 행을 추가하고 numpy로 변환하는 것이 훨씬 빠릅니다. 다음은 Python 3.6과 numpy 1.14를 사용하여 한 번에 하나씩 100 행을 추가하는 타이밍 테스트입니다.

import numpy as py
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.


import numpy as np
array_ = np.array([[1,2,3]])
add_row = np.array([[4,5,6]])

array_ = np.concatenate((array_, add_row), axis=0)

I use 'np.vstack' which is faster, EX:

import numpy as np

input_array=np.array([1,2,3])
new_row= np.array([4,5,6])

new_array=np.vstack([input_array, new_row])

If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:

A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
    newrow = np.arange(3)+i
    if i%5:
        Alist.append(newrow)
A = np.array(Alist)
del Alist

Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.


You can use numpy.append() to append a row to numpty array and reshape to a matrix later on.

import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
# in your example
A = [1,2]
for row in X:
    A = np.append(A, row)

참고URL : https://stackoverflow.com/questions/3881453/numpy-add-row-to-array

반응형