Python Forum
Finding Row Number for Items in 2D array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Finding Row Number for Items in 2D array (/thread-15256.html)



Finding Row Number for Items in 2D array - fafzal - Jan-10-2019

Hi everyone. First post here because I'm completely stuck on my homework assignment. I don't have a strong coding background so any help is greatly appreciated.

I have a set of 25 randomly generated numbers. The array is shaped 5 x 5.
I need to be able to multiply the numbers in each row with it's row numbers.
All numbers in row 1 x 1, all numbers in row 2 x 2 etc.

Here is what I have and I'm not sure how to get the address (row number) for every item in the array:

import random
mu, stdev = 5, 5
random.seed(1)
three = np.random.normal(mu, stdev, 25).reshape(5,5)

for x in three: 
    y = x * x.shape[0]
    print (x.shape[0])



RE: Finding Row Number for Items in 2D array - scidam - Jan-10-2019

No loops needed. Numpy can do all the work by itself:

three = three * np.arange(three.shape[0])[:, np.newaxis] # 0-based numbering
# or 
three = three * np.arange(1, three.shape[0] + 1)[:, np.newaxis] # 1-based numbering



RE: Finding Row Number for Items in 2D array - fafzal - Jan-10-2019

(Jan-10-2019, 05:57 AM)scidam Wrote: No loops needed. Numpy can do all the work by itself:
three = three * np.arange(three.shape[0])[:, np.newaxis] # 0-based numbering # or three = three * np.arange(1, three.shape[0] + 1)[:, np.newaxis] # 1-based numbering 
This works neatly but I'm sorry I should have mentioned that I'm asked to do this using indexing and looping.

I was able to find a way and wanted to post back. Here's what worked
Thanks for the help

for i in range (0,5):
    three[i]=three[i]*(i+1)