0
0
NumPydata~10 mins

Set operations on structured data 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 create a structured numpy array with fields 'name' and 'age'.

NumPy
import numpy as np

data = np.array([('Alice', 25), ('Bob', 30)], dtype=[1])
Drag options to blanks, or click blank then click option'
A('name', 'U10'), ('age', 'i4')
B['name', 'age']
C{'name': 'U10', 'age': 'i4'}
D[('name', 'U10'), ('age', 'i4')]
Attempts:
3 left
💡 Hint
Common Mistakes
Using a tuple instead of a list for dtype
Using a dictionary instead of a list of tuples
Not specifying the dtype at all
2fill in blank
medium

Complete the code to find the union of two structured numpy arrays 'a' and 'b'.

NumPy
import numpy as np

a = np.array([(1, 'A'), (2, 'B')], dtype=[('id', 'i4'), ('val', 'U1')])
b = np.array([(2, 'B'), (3, 'C')], dtype=[('id', 'i4'), ('val', 'U1')])

union = np.[1](a, b)
Drag options to blanks, or click blank then click option'
Aunion1d
Bsetdiff1d
Cin1d
Dintersect1d
Attempts:
3 left
💡 Hint
Common Mistakes
Using intersect1d which finds common elements only
Using setdiff1d which finds difference
Using in1d which returns boolean mask
3fill in blank
hard

Fix the error in the code to find the intersection of two structured arrays 'x' and 'y'.

NumPy
import numpy as np

x = np.array([(1, 10), (2, 20)], dtype=[('id', 'i4'), ('score', 'i4')])
y = np.array([(2, 20), (3, 30)], dtype=[('id', 'i4'), ('score', 'i4')])

common = np.[1](x, y)
Drag options to blanks, or click blank then click option'
Aunion1d
Bintersect1d
Csetxor1d
Dsetdiff1d
Attempts:
3 left
💡 Hint
Common Mistakes
Using union1d which returns all unique elements
Using setxor1d which returns symmetric difference
Using setdiff1d which returns difference
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.

NumPy
words = ['data', 'science', 'ai', 'ml']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of length
Checking if word > 3 which is invalid
Not using len(word) in condition
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their values only if the value is greater than 0.

NumPy
data = {'a': 1, 'b': -1, 'c': 3}
result = [1]: [2] for k, v in data.items() if v [3] 0}
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using k.lower() instead of k.upper()
Using '<' instead of '>' in condition
Mapping keys instead of values