2

I want to add a new column one by one, and I simplified my code:

import numpy as np
score = [[99], [99]]
for j in range (5):
    temp = []
    for i in range (2):
        temp.append(i)
    temp = np.array(temp)
    score = np.c_[score, temp.T]
score = np.delete(score, obj=0, axis=1)
print(score)

I want to add a new column [1, 2].T at each step, so that the array looks like this:

[1] -> [1, 1] -> ...
[2]    [2, 2]

However, I have to create the first column [[99], [99]] and delete it in the end. Is there some better method can skip this step?

2
  • Do another layer of list append. At the end make the 2d array and transpose if necessary. Commented Feb 2, 2021 at 16:20
  • For one thing, you can start with score = np.empty((2, 0) instead of [[99], [99]]. For another, lists and deques are much better at appending than numpy arrays. Your loop is making me cry inside a little. Commented Feb 2, 2021 at 22:12

1 Answer 1

1

To answer your literal question, you can create empty lists or arrays as placeholders:

score = [[], []]
score = np.empty((2, 0))
score = np.array([[], []])
...

Numpy arrays are not a good tool for appending. Make an array once the data is at a fixed size. Assuming that you don't know how many columns you will have, something like this is OK:

score = [[], []]
for j in range(5):
    for i, row in zip(range(2), score):
        row.append(i)
score = np.array(score)

Or better yet:

score = []
for j in range(5):
    score.append(list(range(2)))
score = np.array(score).T

If you want a C-contiguous result, replace the last line with

score = np.array(score, order='F').T
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.