Recall & Review
beginner
What does the
apply() function do when used with axis=1 in pandas?It applies a function to each row of the DataFrame, allowing you to perform row-wise operations.
Click to reveal answer
beginner
How do you specify that
apply() should work on rows instead of columns?By setting the parameter
axis=1 inside the apply() function.Click to reveal answer
beginner
Example: What will this code do?<br>
df.apply(lambda row: row['A'] + row['B'], axis=1)
It will add the values in columns 'A' and 'B' for each row and return a Series with these sums.
Click to reveal answer
intermediate
Why might you use
apply() with axis=1 instead of vectorized operations?To perform custom or complex operations that involve multiple columns in each row, which are not easily done with simple vectorized functions.
Click to reveal answer
beginner
What type of object does the function inside
apply(axis=1) receive as input?It receives a pandas Series representing a single row of the DataFrame.
Click to reveal answer
What does
axis=1 mean when used with apply() in pandas?✗ Incorrect
Setting axis=1 tells pandas to apply the function to each row.
What type of object is passed to the function inside
apply(axis=1)?✗ Incorrect
The function receives a Series object representing one row of the DataFrame.
Which of these is a correct way to sum columns 'A' and 'B' for each row using
apply()?✗ Incorrect
Using apply() with axis=1 and a lambda function sums columns 'A' and 'B' row-wise.
Why might
apply(axis=1) be slower than vectorized operations?✗ Incorrect
apply(axis=1) often uses Python-level loops, which are slower than vectorized operations.
If you want to create a new column based on row-wise calculations, which method is suitable?
✗ Incorrect
Using apply() with axis=1 lets you compute values row-wise for a new column.
Explain how
apply() with axis=1 works in pandas and give a simple example.Think about how you would add two columns for each row.
You got /4 concepts.
Describe a situation where using
apply() with axis=1 is better than vectorized operations.Consider when you need custom calculations per row.
You got /3 concepts.