简体   繁体   中英

How to change all odd values of a array to their negative e.g. 1 should be -1 by fancy indexing?

I'm trying to understand the fancy indexing using numpy and still facing some problem.

I have tried to solve the problem I have odd -ve values from given array need to understand how to replace +ve odd to -ve odd in a given array. Reshape is not working

import numpy as np
from numpy import reshape

v = np.arange(1, 91, 1)
print(v)
print("\n")

v1 = ((v[v%2==1])* (-1))
print (v1)
print("\n")

#val = np.arange(1, 91, 1).reshape(6,6)
#print(val)
#print("\n")

This is the error message ValueError: cannot reshape array of size 90 into shape (6,6)

You select all odd ones and multiply them by -1:

import numpy as np

v1 = np.arange(1, 91, 1) 
v1[v1%2==1] *= -1          # select & multiply only odd indexes, don't effect even ones

print (v1)

Output:

[ -1   2  -3   4  -5   6  -7   8  -9  10 -11  12 -13  14 -15  16 -17  18
 -19  20 -21  22 -23  24 -25  26 -27  28 -29  30 -31  32 -33  34 -35  36
 -37  38 -39  40 -41  42 -43  44 -45  46 -47  48 -49  50 -51  52 -53  54
 -55  56 -57  58 -59  60 -61  62 -63  64 -65  66 -67  68 -69  70 -71  72
 -73  74 -75  76 -77  78 -79  80 -81  82 -83  84 -85  86 -87  88 -89  90]

Your given error stems from reshaping 90 elements into 6*6 elements (ie not possible). Your v1 is

[ -1  -3  -5  -7  -9 -11 -13 -15 -17 -19 -21 -23 -25 -27 -29 
 -31 -33 -35 -37 -39 -41 -43 -45 -47 -49 -51 -53 -55 -57 -59 
 -61 -63 -65 -67 -69 -71 -73 -75 -77 -79 -81 -83 -85 -87 -89]

because you select the odd ons, multiply by -1 and assign them - the even ones do not get assigned. These are still 45 values - not 36.

You cannot reshape 90 elements int 6*6 (36) elements. You could do:

print( np.arange(1, 91, 1).reshape(9,10) ) # reshape 90 elemens into 10*9 elems

[[ 1  2  3  4  5  6  7  8  9 10]
 [11 12 13 14 15 16 17 18 19 20]
 [21 22 23 24 25 26 27 28 29 30]
 [31 32 33 34 35 36 37 38 39 40]
 [41 42 43 44 45 46 47 48 49 50]
 [51 52 53 54 55 56 57 58 59 60]
 [61 62 63 64 65 66 67 68 69 70]
 [71 72 73 74 75 76 77 78 79 80]
 [81 82 83 84 85 86 87 88 89 90]]

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