Reputation: 460
Let's say I've initialized a matrix/array that has 400 rows, 3 columns:
distances = np.zeros([400, 3], dtype=np.float64)
Now, I have a for loop that returns 1200 objects (float values) and I want to "append" each element into distances
(row by row) or assign those float values to each element in the matrix like:
distances[0,1] = item1,
distances[0,2] = item2,
distances[0,3] = item3,
distances[1,1] = item4,
distances[1,2] = .....
How can I do this? I tried numpy.append
and numpy.insert
but I failed. Any ideas?
Upvotes: 0
Views: 48
Reputation: 104102
If you want random access, you can do it with enumeration (to get row by row access) and slice assignment:
distances = np.zeros([400, 3], dtype=np.float64)
start=[1,2,3]
for i,_ in enumerate(distances):
distances[i][:]=start
start=[x+1 for x in start]
>>> distances
[[ 1. 2. 3.]
[ 2. 3. 4.]
[ 3. 4. 5.]
...,
[ 398. 399. 400.]
[ 399. 400. 401.]
[ 400. 401. 402.]]
Upvotes: 1
Reputation: 85612
Gather you items in a list, convert this list into NumPy array and reshape:
distances = np.array([item1, item2, ... item1200], dtype=float).reshape((400, 3))
Upvotes: 1