arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[arr % 2 == 1] = -1
print(arr)
o/p:
#> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
arr = np.arange(10)
out = np.where(arr % 2 == 1, -1, arr)
print('Original : ',arr)
print('Changed ':out)
#> Original : [0 1 2 3 4 5 6 7 8 9]
Changed : array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr = np.arange(12)
arr.reshape(4, 3) # Setting to -1 means (4,-1) automatically decides the number of cols
print(arr)
#> array([[0, 1, 2, 3],
[4, 5, 6, 7]
[8, 9, 10, 11]])
Solution
a = np.arange(10).reshape(2,5)
b = np.repeat(2, 10).reshape(2,5)
# Method 2:
np.concatenate([a, b], axis=0)
# Method 2:
np.vstack([a, b])
# Method 3:
np.r_[a, b]
#> array([[0, 1, 2, 3, 4],
#> [5, 6, 7, 8, 9],
#> [2, 2, 2, 2, 2],
#> [2, 2, 2, 2, 2]])
Solution
a = np.arange(10).reshape(2,5)
b = np.repeat(2, 10).reshape(2,5)
# Method 2:
np.concatenate([a, b], axis=2)
# Method 2:
np.hstack([a, b])
# Method 3:
np.c_[a, b]
#> array([[0, 1, 2, 3, 4, 2, 2, 2, 2, 2],
#> [5, 6, 7, 8, 9, 2, 2, 2, 2, 2]])
a = np.array([1,2,3])`
Desired Output:
#> array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
Solution
np.r_[np.repeat(a, 3), np.tile(a, 3)]
#> array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
Get the common items between a and b
Input:
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
Desired Output:
array([2, 4])
Solution
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
np.intersect1d(a,b)
#> array([2, 4])
Note: From array a remove all items present in array b.
Input:
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
Desired Output:
array([1,2,3,4])
Solution
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
# From 'a' remove all of 'b'
np.setdiff1d(a,b)
#> array([1, 2, 3, 4])
Note: Get the positions where elements of a and b match.
Input:
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
Desired Output:
#> (array([1, 3, 5, 7]),)
Solution
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
np.where(a == b)
#> (array([1, 3, 5, 7]),)
Note: Get all items between 5 and 10 from a.
Input:
a = np.array([2, 6, 1, 9, 10, 3, 27])
Desired Output:
(array([6, 9, 10]),)
Solution
a = np.arange(15)
# Method 1
index = np.where((a >= 5) & (a <= 10))
a[index]
# Method 2:
index = np.where(np.logical_and(a>=5, a<=10))
a[index]
#> (array([6, 9, 10]),)
# Method 3: (thanks loganzk!)
a[(a >= 5) & (a <= 10)]