简体   繁体   中英

change the value of a numpy array to a different data type

I have the following code that seeks to change the number 4 on the matrix (if 4 is rolled) to an 'x'. This can be done with Python lists, but numpy arrays require the same data type. Is there a workaround, that allows me to achieve the same result?

Code

import numpy as np 

matrix=np.array([[9,10,11,12],[8,7,6,5],[1,2,3,4]])
print(matrix)

def round1():
    rolldice=int(input("Roll Dice:"))
    print("You have rolled:",rolldice)
    if rolldice<=4:
        matrix[2,rolldice-1]="X"
        print(matrix)
    else:
        print("Greater than 3")

round1()

Line that doesn't work:

if rolldice<=4:
    matrix[2,rolldice-1]="X"

What would work (this would change it to a zero)

if rolldice<=4:
    matrix[2,rolldice-1]=0

Any ideas on how this could be done? I simply, based on the number rolled by the dice, want to replace the number in the matrix with an 'x'. So if 3 was rolled, 3 would be replaced by an 'x'.

As an aside, I'd also be interested in a more efficient way of replacing the relevant number in the matrix with an x based on the throw, without the use of IF functions. At the moment, I have to specify that if the throw is less than 4 (which is the length of the third list in the array), do such and such, else, I would have to go on to code another alternative for if the throw exceeded 4.

With NumPy's masked array utility, you can probably achieve the same functionality, as follows:

In [1]: matrix = np.ma.array([[9,10,11,12],[8,7,6,5],[1,2,3,4]])

In [2]: matrix
Out[2]:
masked_array(data =
 [[ 9 10 11 12]
 [ 8  7  6  5]
 [ 1  2  3  4]],
             mask =
 False,
       fill_value = 999999)

In [3]: matrix.mask |= matrix.data == 4

In [4]: matrix
Out[4]:
masked_array(data =
 [[9 10 11 12]
 [8 7 6 5]
 [1 2 3 --]],
             mask =
 [[False False False False]
 [False False False False]
 [False False False  True]],
       fill_value = 999999)

In [5]: matrix.mask |= matrix.data == 9

In [6]: matrix
Out[6]:
masked_array(data =
 [[-- 10 11 12]
 [8 7 6 5]
 [1 2 3 --]],
             mask =
 [[ True False False False]
 [False False False False]
 [False False False  True]],
       fill_value = 999999)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM