Acee
Acee

Reputation: 109

Append function in numpy array

I need help for my project. I have an array that look like this?

rndm = [[0 1]
        [0 0]
        [0 0]
        [0 1]]

Now, I want to add par_1 = [[1 0]], par_2 = [[0 0], ch1 = [[1 1]], and ch2 = [[0 1]] to rndm.

My code looks like this:

new_rndm = []
new_rndm.append(par_1)
new_rndm.append(par_2)
new_rndm.append(ch1)
new_rndm.append(ch2)
# add them to rndm
rndm = numpy.append(rndm, [new_rndm])
print(rndm)

The output gives me something like this:

rndm = [0 1 0 0 0 0 0 1 1 0 0 0 1 1 0 1]

What I am expecting as my out put is:

rndm = [[0 1]
        [0 0]
        [0 0]
        [0 1]
        [1 0]
        [0 0]
        [1 1]
        [0 1]]

I think the problem is that append cannot be used in arrays. If correct, anyone help me what other function I could try? If not, kindly educate me. I am very much willing to learn. Thank you!

Upvotes: 0

Views: 110

Answers (3)

Pygirl
Pygirl

Reputation: 13349

Use np.append(<array>, <elem to append>, axis=0)

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

par_1 = [[1, 0]]; par_2 = [[0, 0]]; ch1 = [[1, 1]]; ch2 = [[0, 1]]

rndm = np.append(rndm, par_1, axis=0)
rndm = np.append(rndm, par_2, axis=0)
rndm = np.append(rndm, ch1, axis=0)
rndm = np.append(rndm, ch2, axis=0)

array([[0, 1],
       [0, 0],
       [0, 0],
       [0, 1],
       [1, 0],
       [0, 0],
       [1, 1],
       [0, 1]])

Edit:

Reshape:

x = np.array([2,1])
y = x.reshape(-1,1) # <------------ you have to do this
x.shape, y.shape

((2,), (2, 1))

Upvotes: 3

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

You can use ordinary list appending to generate the desired nested list structure:

rndm = [[0, 1],
        [0, 0],
        [0, 0],
        [0, 1]
        ]

par_1 = [[1, 0]]
par_2 = [[0, 0]]
ch1 = [[1, 1]]
ch2 = [[0, 1]]

new_rndm = []

new_rndm.append(par_1)
new_rndm.append(par_2)
new_rndm.append(ch1)
new_rndm.append(ch2)

new_rndm = [i for k in new_rndm for i in k]

for data in new_rndm:
    rndm.append(data)

for data in rndm:
    print(data)

Outputs:

[0, 1]
[0, 0]
[0, 0]
[0, 1]
[1, 0]
[0, 0]
[1, 1]
[0, 1]

Upvotes: 0

sugarfi
sugarfi

Reputation: 127

You can use .append to add an array to the end of another array. The problem here is that numpy.append flattens the array first, ie. numpy.append([1 0], [0 1]) is [1 0 0 1]. See the numpy docs on .append.

Upvotes: 0

Related Questions