0
0
NumPydata~10 mins

np.in1d() for membership testing in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check which elements of array1 are in array2 using np.in1d().

NumPy
import numpy as np
array1 = np.array([1, 2, 3, 4])
array2 = np.array([3, 4, 5, 6])
result = np.in1d(array1, [1])
print(result)
Drag options to blanks, or click blank then click option'
Aarray2
Barray1
C[3, 4]
Dnp.array([1, 2])
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same array for both arguments.
Passing a list instead of a numpy array.
2fill in blank
medium

Complete the code to get a boolean array showing membership of elements in arr1 within arr2.

NumPy
import numpy as np
arr1 = np.array(['apple', 'banana', 'cherry'])
arr2 = np.array(['banana', 'date', 'fig'])
membership = np.in1d(arr1, [1])
print(membership)
Drag options to blanks, or click blank then click option'
Aarr2
B['banana', 'date']
Carr1
D['apple', 'fig']
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the arrays in the function call.
Passing a list instead of a numpy array.
3fill in blank
hard

Fix the error in the code to correctly test membership using np.in1d().

NumPy
import numpy as np
x = np.array([10, 20, 30])
y = np.array([20, 40, 60])
result = np.in1d([1], y)
print(result)
Drag options to blanks, or click blank then click option'
Ay
Bnp.array([20, 40])
C[10, 20]
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of arrays in np.in1d.
Passing a list instead of a numpy array.
4fill in blank
hard

Fill both blanks to create a dictionary showing elements of words and whether their length is greater than 5 and if they are in the list check_list using np.in1d().

NumPy
words = ['apple', 'banana', 'cherry', 'date']
check_list = ['banana', 'date', 'fig']
result = {word: (len(word) [1] 5 and np.in1d([word], [2])[0]) for word in words}
print(result)
Drag options to blanks, or click blank then click option'
A>
B<
Ccheck_list
Dwords
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator.
Checking membership against the wrong list.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their membership boolean in check_words if their length is less than 6.

NumPy
words = ['apple', 'banana', 'cherry', 'date']
check_words = ['APPLE', 'DATE', 'FIG']
result = {word[1]: np.in1d([word[2]], [3])[0] for word in words if len(word) < 6}
print(result)
Drag options to blanks, or click blank then click option'
A.upper()
B.lower()
Ccheck_words
Dwords
Attempts:
3 left
💡 Hint
Common Mistakes
Using .lower() instead of .upper().
Checking membership against the wrong list.