0
0
NumPydata~10 mins

Structured arrays vs DataFrames in NumPy - Interactive 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 array with fields 'name' and 'age'.

NumPy
import numpy as np

people = 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', 'S10'), ('age', 'f4')]
C[('name', 'U5'), ('age', 'i2')]
D[('name', 'U10'), ('age', 'f8')]
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect data types like float for age.
Not using a list of tuples for dtype.
2fill in blank
medium

Complete the code to convert the structured array 'people' to a pandas DataFrame.

NumPy
import pandas as pd

df = pd.DataFrame([1])
Drag options to blanks, or click blank then click option'
Apeople.tolist()
Bpeople.astype(object)
Cpeople.view(np.recarray)
Dpeople
Attempts:
3 left
💡 Hint
Common Mistakes
Converting to list loses field names.
Using .view(np.recarray) unnecessarily.
3fill in blank
hard

Fix the error in accessing the 'age' field from the structured array 'people'.

NumPy
ages = people[1]
Drag options to blanks, or click blank then click option'
A.age
B[1]
C['age']
D['Age']
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation which does not work for numpy structured arrays.
Using incorrect capitalization in field names.
4fill in blank
hard

Fill all four blanks to create a DataFrame from a dictionary comprehension that filters people older than 25.

NumPy
df_filtered = pd.DataFrame([1]: [2] for [3] in people if [4] > 25)
Drag options to blanks, or click blank then click option'
Aperson['name']
Bperson['age']
Cperson
Dp
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong field for keys or values.
Not filtering correctly with the age condition.
5fill in blank
hard

Fill all three blanks to create a structured array from a list of tuples and then convert it to a DataFrame.

NumPy
data = [('John', 28), ('Jane', 32)]

arr = np.array(data, dtype=[[1], [2]])
df = pd.DataFrame([3])
Drag options to blanks, or click blank then click option'
A('name', 'U10')
B('age', 'i4')
Carr
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the original list to pd.DataFrame instead of the structured array.
Incorrect dtype format.