4daJKong
4daJKong

Reputation: 2045

How to append new column without creating an array in advance?

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?

Upvotes: 2

Views: 315

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114350

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

Upvotes: 1

Related Questions