I have a 2d array, I would like to set a column to a particular value, my code is below. Is this the best way in python?
rows = 5
cols = 10
data = (rows * cols) *[0]
val = 10
set_col = 5
for row in range(rows):
data[row * cols + set_col - 1] = val
If I want to set a number of columns to a particular value , how could I extend this
I would like to use the python standard library only
Thanks
int contents[][] = new int[2][2]; contents[0][0] = 1; contents[1][1] = 2; ... That will let you individual assign values to elements in your 2D array, one at a time.
Select a single element from 2D Numpy Array by index We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.
NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.
A better solution would be:
data = [[0] * cols for i in range(rows)]
For the values of cols = 2
, rows = 3
we'd get:
data = [[0, 0],
[0, 0],
[0, 0]]
Then you can access it as:
v = data[row][col]
Which leads to:
val = 10
set_col = 5
for row in range(rows):
data[row][set_col] = val
Or the more Pythonic (thanks J.F. Sebastian):
for row in data:
row[set_col] = val
NumPy package provides powerful N-dimensional array object. If data
is a numpy
array then to set set_col
column to val
value:
data[:, set_col] = val
Complete Example:
>>> import numpy as np
>>> a = np.arange(10)
>>> a.shape = (5,2)
>>> a
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> a[:,1] = -1
>>> a
array([[ 0, -1],
[ 2, -1],
[ 4, -1],
[ 6, -1],
[ 8, -1]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With