Python - best way to set a column in a 2d array to a specific value
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) 开发者_JAVA百科*[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
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]])
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
There's nothing inherently wrong with the way you're using, except that it would be clearer to name the variableset_col
than set_row
since you're setting a column.
So set a number of columns, just wrap it with another loop:
for set_col in [...columns that have to be set...]
One concern, though: your 2D array is unusual in that it's packed in a 1D array (Python can support 2D arrays via lists of lists as well), so I would wrap it all with methods or functions.
In your case rows and columns are probably interchangeable, i.e. it's matter of semantics which is which. If this is the case, then you could make columns to occupy sequence of cells in data
list, and then zero them using just:
data[column_start:column_start+rows] = rows * [0]
An earlier answer left out a range
, so you could try the following:
cols = 7
rows = 8
data = [[0] * cols for i in range(rows)]
val = 10
set_col = 5
for row in data:
row[set_col] = val
to extend this to a number of columns you could store the column number and it's value in a dict
. So to set colum 5 to 10 and column 2 to 7:
cols = 7
rows = 8
data = [[0] * cols for i in range(rows)]
valdict = {5:10, 2:7}
for col, val in valdict.items():
for row in data:
row[col] = val
Swapping the rows and columns, as suggested in another answer, makes this slightly simpler:
cols = 7
rows = 8
data = [[0] * rows for i in range(cols)]
valdict = {5:10, 2:7}
for col, val in valdict.items():
data[col] = [val] * rows
精彩评论