IT박스

numpy 배열을 초기화

itboxs 2020. 8. 5. 08:02
반응형

numpy 배열을 초기화


모양의 numpy 배열을 초기화하고 추가하는 방법이 있습니까? 리스트 예제로 필요한 것을 설명하겠습니다. 루프에서 생성 된 객체 목록을 만들려면 다음을 수행하십시오.

a = []
for i in range(5):
    a.append(i)

numpy 배열과 비슷한 것을하고 싶습니다. vstack, concatenate 등에 대해 알고 있지만 입력으로 두 개의 numpy 배열이 필요한 것 같습니다. 내가 필요한 것은 :

big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
    array i of shape = (2,4) created.
    add to big_array

big_array모양 있어야합니다 (10,4). 이것을하는 방법?


편집하다:

다음 설명을 추가하고 싶습니다. 나는 big_array = numpy.zeros((10,4))그것을 정의 하고 채울 수 있다는 것을 알고 있습니다 . 그러나 big_array의 크기를 미리 지정해야합니다. 이 경우 크기를 알고 있지만, 그렇지 않으면 어떻게합니까? .append파이썬에서 목록을 확장 하는 함수를 사용할 때 최종 크기를 미리 알 필요가 없습니다. 빈 배열로 시작하여 작은 배열에서 더 큰 배열을 만들 때 비슷한 것이 있는지 궁금합니다.


numpy.zeros

0으로 채워진 지정된 모양과 유형의 새 배열을 반환합니다.

또는

numpy.ones

주어진 모양과 유형으로 채워진 새로운 배열을 반환합니다.

또는

numpy.empty

항목을 초기화하지 않고 지정된 모양과 유형의 새 배열을 반환합니다.


그러나 요소를 목록에 추가하여 배열을 구성하는 방식은 numpy에서는 그다지 효율적이지 않기 때문에 많이 사용되지 않습니다 (numpy 데이터 유형은 기본 C 배열에 훨씬 더 가깝습니다). 대신 필요한 크기로 배열을 미리 할당 한 다음 행을 채워야합니다. numpy.append그래도 필요한 경우 사용할 수 있습니다 .


내가 일반적으로하는 방법은 일반 목록을 만든 다음 내 물건을 추가하고 다음과 같이 목록을 numpy 배열로 변환하는 것입니다.

import numpy as np
big_array = [] #  empty regular list
for i in range(5):
    arr = i*np.ones((2,4)) # for instance
    big_array.append(arr)
big_np_array = np.array(big_array)  # transformed to a numpy array

물론 최종 객체는 생성 단계에서 메모리 공간의 두 배를 차지하지만 파이썬 목록에 추가하는 것은 매우 빠르며 np.array ()를 사용하여 생성하는 것도 가능합니다.


numpy 1.8에 도입 :

numpy.full

fill_value로 채워진 지정된 모양과 유형의 새 배열을 반환합니다.

예 :

>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])

파이썬의 배열 아날로그

a = []
for i in range(5):
    a.append(i)

입니다 :

import numpy as np

a = np.empty((0))
for i in range(5):
    a = np.append(a, i)

numpy.fromiter() 당신이 찾고있는 것입니다 :

big_array = numpy.fromiter(xrange(5), dtype="int")

It also works with generator expressions, e.g.:

big_array = numpy.fromiter( (i*(i+1)/2 for i in xrange(5)), dtype="int" )

If you know the length of the array in advance, you can specify it with an optional 'count' argument.


You do want to avoid explicit loops as much as possible when doing array computing, as that reduces the speed gain from that form of computing. There are multiple ways to initialize a numpy array. If you want it filled with zeros, do as katrielalex said:

big_array = numpy.zeros((10,4))

EDIT: What sort of sequence is it you're making? You should check out the different numpy functions that create arrays, like numpy.linspace(start, stop, size) (equally spaced number), or numpy.arange(start, stop, inc). Where possible, these functions will make arrays substantially faster than doing the same work in explicit loops


For your first array example use,

a = numpy.arange(5)

To initialize big_array, use

big_array = numpy.zeros((10,4))

This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.

Edit: If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist). The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.


Whenever you are in the following situation:

a = []
for i in range(5):
    a.append(i)

and you want something similar in numpy, several previous answers have pointed out ways to do it, but as @katrielalex pointed out these methods are not efficient. The efficient way to do this is to build a long list and then reshape it the way you want after you have a long list. For example, let's say I am reading some lines from a file and each row has a list of numbers and I want to build a numpy array of shape (number of lines read, length of vector in each row). Here is how I would do it more efficiently:

long_list = []
counter = 0
with open('filename', 'r') as f:
    for row in f:
        row_list = row.split()
        long_list.extend(row_list)
        counter++
#  now we have a long list and we are ready to reshape
result = np.array(long_list).reshape(counter, len(row_list)) #  desired numpy array

I realize that this is a bit late, but I did not notice any of the other answers mentioning indexing into the empty array:

big_array = numpy.empty(10, 4)
for i in range(5):
    array_i = numpy.random.random(2, 4)
    big_array[2 * i:2 * (i + 1), :] = array_i

This way, you preallocate the entire result array with numpy.empty and fill in the rows as you go using indexed assignment.

It is perfectly safe to preallocate with empty instead of zeros in the example you gave since you are guaranteeing that the entire array will be filled with the chunks you generate.


I'd suggest defining shape first. Then iterate over it to insert values.

big_array= np.zeros(shape = ( 6, 2 ))
for it in range(6):
    big_array[it] = (it,it) # For example

>>>big_array

array([[ 0.,  0.],
       [ 1.,  1.],
       [ 2.,  2.],
       [ 3.,  3.],
       [ 4.,  4.],
       [ 5.,  5.]])

To initialize a numpy array with a specific matrix:

import numpy as np

mat = np.array([[1, 1, 0, 0, 0],
                [0, 1, 0, 0, 1],
                [1, 0, 0, 1, 1],
                [0, 0, 0, 0, 0],
                [1, 0, 1, 0, 1]])

print mat.shape
print mat

output:

(5, 5)
[[1 1 0 0 0]
 [0 1 0 0 1]
 [1 0 0 1 1]
 [0 0 0 0 0]
 [1 0 1 0 1]]

Maybe something like this will fit your needs..

import numpy as np

N = 5
res = []

for i in range(N):
    res.append(np.cumsum(np.ones(shape=(2,4))))

res = np.array(res).reshape((10, 4))
print(res)

Which produces the following output

[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]]

참고URL : https://stackoverflow.com/questions/4535374/initialize-a-numpy-array

반응형