Reputation: 1311
My question is simple: what is the most efficient (preferred) method in Python to create an array and fill it with values column by column?
First thing that comes into my mind is just to create array empty array (or array filled with zeros) and step by step fill it based on column number.
import random
import numpy as np
values = np.zeros([10, 20])
# or values = np.empty([10,20])
for i in range(len(values.T)):
if i == 0:
values[:,i] = 1
elif i < 10:
values[:,i] = random.sample(range(1, 100), 10)
else:
values[:,i] = values[:,i] - values[:,i - 1] * i
EDIT: What I am filling the columns with is not as important here as the most efficent way to do it.
Upvotes: 2
Views: 195
Reputation: 10759
You could use resize:
values = np.zeros([20])
for i in range(len(values)):
if i == 0:
values[i] = 1
elif i < 10:
values[i] = random.sample(range(1, 100), 1)
else:
values[i] = values[i] - values[i - 1] * i
values = np.resize(values, [10, 20])
This is efficient since it mostly works on small arrays, defining each column, and then performs only one operation in order to create a larger array.
Upvotes: 1