Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) *[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

like image 902
mikip Avatar asked Feb 05 '10 12:02

mikip


People also ask

How do you assign a single value to a 2D array?

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.

How do I select a column in NumPy 2D array?

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.

How do you sort a 2D NumPy array based on one column?

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.


2 Answers

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
like image 181
Max Shawabkeh Avatar answered Oct 02 '22 09:10

Max Shawabkeh


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]])
like image 35
jfs Avatar answered Oct 02 '22 10:10

jfs