More "modern python" way of doing things.

[[ randint(0,4) for x in range(0,4)] for y in range(0,4)]

Its simply a pair of nested list comprehensions.

Answer from Shayne on Stack Overflow
๐ŸŒ
Snakify
snakify.org โ€บ two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
The thing is, if the number 0 is replaced by some expression that depends on i (the line number) and j (the column number), you get the matrix filled according to some formula. For example, suppose you need to initialize the following array (for convenience, extra spaces are added between items):
Discussions

python - Filling a 2D Array with Another Array - Stack Overflow
I am trying to fill a 2D array using a for loop, with a variable that is an array. From this array, I am hoping to find the average of each column and input this into a new array. However, I don't... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to populate a 2d array? - Stack Overflow
I have the following code that (nearly) populates a list of lists (I will call it a 2d array) in Python. Instead of going up from 0-6 and repeating this 3 times, I want it to populate the array w... More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 9, 2017
How to fill each element of a 2d array with a for loop in python - Stack Overflow
Whats happening is the loop is iterating and filling the elements of the array, but 'element wise' - ie it is calculating the first element correctly, then looping again and filling the first element More on stackoverflow.com
๐ŸŒ stackoverflow.com
fill 2d array python value from a list / 1d array - Stack Overflow
OR put directly the b value into 2D array whic one colum represent loop for number of k. *My difficulties here is, k is not integer. its dict keys (str). whose length=9 ... row = len(data.items()) matrix=np.zeros((9,2)) for i in range (1,3) : a=[] for k, v in data.items(): b=v/sumcount matrix[x][i].fill... More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 25, 2022
๐ŸŒ
CodePal
codepal.ai โ€บ code-generator โ€บ query โ€บ eHoNZVXS โ€บ fill-2d-array-python
Fill 2D Array in Python - CodePal
""" # Create a 7x7 2D array filled ... the array filled_array = fill_array() ... In Python, you can fill a 2D array using loops and a specific pattern....
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to create a two dimensional array in python?
How To Create a Two Dimensional Array in Python? - Be on the Right Side of Change
June 11, 2022 - Another way of creating 2D arrays in Python without using an external module is to use Python dictionaries. Dictionary acts as a placeholder to contain all the elements of the array. โœ‰๏ธ๏ธNote: This approach is best suited only when you need to have a separate container to hold the values and the cells of the 2D array. If you have many operations to be performed on the array, this can get complicated, and it is not recommended in such cases. Example: We are creating an empty dictionary array_2d and then filling in values.
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ two-dimensional-array-in-python
Two Dimensional Array in Python - AskPython
August 6, 2022 - Output-Append 2D Array ยท Array slicing is used to access multiple values within an array. Syntax: <slice_array> = <array>[start:stop] array1 = [[1,2,3],[4,5,6,7]] #python array slice array2 = array1[1:3] #index 1 to 2 print(array2) array2 = array1[:1] #index 0 to 1 print(array2) Output: Output-Slicing 2D Array ยท
Top answer
1 of 2
1

Are you necessarily looking to use for-loops? I am asking because this problem can be solved in simpler and more efficient ways such as:

import numpy as np

a_values = np.random.rand(20,402) #Store random values in a_values with a shape of 20 rows and 402 columns
avg_columns = a_values.mean(axis=0) #Calculate the mean of each column 

print(avg_columns)

Documentation for generating random values: numpy.random.rand

EDIT:

I assumed that xa is randomized in each iteration (make sure to replace it with the xa that you are generating). You can initialize an empty a_values array, and add the generated xa array to it in each iteration using np.vstack. For the first iteration, when a_value is empty, I made it equal to xa (if a_values.size else xa).

import numpy as np

a_values = np.array([])

for i in range(20):
  xa = np.random.rand(1,402)
  a_values = np.vstack([a_values, xa]) if a_values.size else xa

avg_columns = a_values.mean(axis=0) #Average of each column

Documentation for vstack: numpy.vstack

2 of 2
1

I don't think you can change the shape of A_values after it's defined. So you should start with:

A_values = numpy.zeros([20,402])

And if your for loop is iterating through the rows, your index should be [i, 1] (numpy array indexes are not like cartesian plane coords).

But you want to change entire rows of A_values, to do this you use just the first index:

A_values[row] = some_row

Remember that "some_row" needs to have the proper lenght, otherwise you get a ValueError.

Your final code will look like this:

A_values = numpy.zeros([20, 402])

for i in range(0,20):
    A_values([i]) = xa

PS: You should describe the errors you are getting and be clearer if you want help with the "xa" values as well...

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 61124174 โ€บ how-to-fill-each-element-of-a-2d-array-with-a-for-loop-in-python
How to fill each element of a 2d array with a for loop in python - Stack Overflow
How to make it such that once the first element is filled, the for loop moves on to the next element and the next value? ... sim_matrix=np.zeros((3,3), dtype=float) for i in range(0,3): for j in range(0,3): for k in range(0,3): for l in range(0,3): sim_matrix[i][j]=node_list_bsc[0][k]['bsc mean value']-node_list_bsc[1][l]['bsc mean value'] #node_list_bsc[x][y]['bsc mean value'] are float values - they are stored in a list of dictionaries, #hence the double indexing ... array([[1.14488261e-08, 1.14488261e-08, 1.14488261e-08], [1.14488261e-08, 1.14488261e-08, 1.14488261e-08], [1.14488261e-08, 1.14488261e-08, 1.14488261e-08]])
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 74916474 โ€บ fill-2d-array-python-value-from-a-list-1d-array
fill 2d array python value from a list / 1d array - Stack Overflow
December 25, 2022 - OR put directly the b value into 2D array whic one colum represent loop for number of k. *My difficulties here is, k is not integer. its dict keys (str). whose length=9 ... row = len(data.items()) matrix=np.zeros((9,2)) for i in range (1,3) : a=[] for k, v in data.items(): b=v/sumcount matrix[x][i].fill(b), for x in range (1, 10)
Top answer
1 of 1
3

You can calculate the sizes ahead in essentially constant time. Just do that, and use numpy.fromiter:

In [1]: import math, from itertools import permutations, chain

In [2]: def n_chose_k(n, k, fac=math.factorial):
    ...:     return fac(n)/fac(n-k)
    ...:

In [3]: def permutations_to_array(r, k):
    ...:     n = len(r)
    ...:     size = int(n_chose_k(n, k))
    ...:     it = permutations(r, k)
    ...:     arr = np.fromiter(chain.from_iterable(it),
    ...:                       count=size,  dtype=int)
    ...:     arr.size = size//k, k
    ...:     return arr
    ...:

In [4]: arr = permutations_to_array(range(1,20), 7)

In [5]: arr.shape
Out[5]: (36279360, 7)

In [6]: arr[0:5]
Out[6]:
array([[ 1,  2,  3,  4,  5,  6,  7],
       [ 1,  2,  3,  4,  5,  6,  8],
       [ 1,  2,  3,  4,  5,  6,  9],
       [ 1,  2,  3,  4,  5,  6, 10],
       [ 1,  2,  3,  4,  5,  6, 11]])

This will work as long as r is limited to sequences with a len.

Edited to add an implementation I cooked up for a generator of batchsize*k chunks, with a trim option!

import math
from itertools import repeat, chain

import numpy as np

def n_chose_k(n, k, fac=math.factorial):
    return fac(n)/fac(n-k)

def permutations_in_batches(r, k, batchsize=None, fill=0, dtype=int, trim=False):
    n = len(r)
    size = int(n_chose_k(n, k))
    if batchsize is None or batchsize > size:
        batchsize = size
    perms = chain.from_iterable(permutations(r, k))
    count = batchsize*k
    remaining = size - count
    while remaining > 0:
        current = np.fromiter(perms, count=count, dtype=dtype)
        current.shape = batchsize, k
        yield current
        remaining -= count
    if remaining: # remaining is negative
        remaining = -remaining
        if not trim:
            padding = repeat(fill, remaining)
            finalcount = count
            finalshape = batchsize, k
        else:
            q = remaining//k # always divisible q%k==0
            finalcount = q*k
            padding = repeat(fill, remaining)
            finalshape = q, k
        current =  np.fromiter(chain(perms, padding), count=finalcount, dtype=dtype)
        current.shape = finalshape
    else: # remaining is 0
        current = np.fromiter(perms, count=batchsize, dtype=dtype)
        current.shape = batchsize, k
    yield current
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 64920081 โ€บ question-about-filling-a-2d-array-in-python
Question about filling a 2D array in Python - Stack Overflow
What I want is to fill a 3*3 array. This code works as intended: arr = [ [] ] * 3 for i in range(3): arr[i] = (list(map(int, input().split()[:3]))) print(arr) But if I write it like this: arr...
Top answer
1 of 2
2

As I explained in my answer to your previous question, you really need to vectorize arbitrary_function.

You can do this by just calling np.vectorize on the function, something like this:

Z = np.vectorize(arbitrary_function)(np.arange(3), np.arange(5).reshape(5, 1))

But that will only give you a small speedup. In your case, since arbitrary_function is doing a huge amount of work (including opening and parsing an Excel spreadsheet), it's unlikely to make enough difference to even notice, much less to solve your performance problem.

The whole point of using NumPy for speedups is to find the slow part of the code that operates on one value at a time, and replace it with something that operates on the whole array (or at least a whole row or column) at once. You can't do that by looking at the very outside loop, you need to look at the very inside loop. In other words, at arbitrary_function.

In your case, what you probably want to do is read the Excel spreadsheet into a global array, structured in such a way that each step in your process can be written as an array-wide operation on that array. Whether that means multiplying by a slice of the array, indexing the array using your input values as indices, or something completely different, it has to be something NumPy can do for you in C, or NumPy isn't going to help you.


If you can't figure out how to do that, you may want to consider not using NumPy, and instead compiling your inner loop with Cython, or running your code under PyPy. You'll still almost certainly need to move the "open and parse a whole Excel spreadsheet" outside of the inner loop, but at least you won't have to figure out how to rethink your problem in terms of vectorized operations, so it may be easier for you.

2 of 2
0
rows = 10
cols = 10
Z = numpy.array([ arbitrary_function(each_point, each_axes) for each_axes in range(cols) for each_point in range(rows) ]).reshape((rows,cols))

maybe?

๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 1539431 โ€บ how-do-i-get-the-code-to-fill-in-2d-array
How do I get the code to fill in 2d array? | Sololearn: Learn to code for FREE!
I am trying to loop through all the elements in a 2d array so that all combinations of 0's and 1's for nine (9) places in each of five-hundred twelve (512) rows are represented. I then am trying to comment out the assignment lines within the function whichOne() in order to see which combination of 0's and 1's causes the assignment statements in whichOne() to yield y=19. Can you help me? Thank you! https://code.sololearn.com/clnrfk2P8lEF ... I get you want an array of 512 values filled out with the 9 bit pattern that equals the value.