0
0
Pandasdata~10 mins

apply() on rows (axis=1) in Pandas - Interactive Code Practice

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

Complete the code to apply a function to each row of the DataFrame.

Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
result = df.apply(lambda row: row['A'] + row['B'], axis=[1])
print(result)
Drag options to blanks, or click blank then click option'
A1
B2
CNone
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=0 applies the function to columns, not rows.
Forgetting to specify axis parameter.
2fill in blank
medium

Complete the code to create a new column 'Sum' by applying a function on each row.

Pandas
import pandas as pd

df = pd.DataFrame({'X': [5, 6], 'Y': [7, 8]})
df['Sum'] = df.apply(lambda row: row['X'] + row['Y'], axis=[1])
print(df)
Drag options to blanks, or click blank then click option'
ANone
B0
C2
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=0 applies function to columns, causing errors or wrong results.
Not assigning the result back to a new column.
3fill in blank
hard

Fix the error in the code to correctly apply a function on rows to get the max value per row.

Pandas
import pandas as pd

df = pd.DataFrame({'P': [10, 20], 'Q': [30, 15]})
max_values = df.apply(lambda row: max(row), axis=[1])
print(max_values)
Drag options to blanks, or click blank then click option'
A2
BNone
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=0 applies function column-wise, not row-wise.
Forgetting to specify axis parameter.
4fill in blank
hard

Fill both blanks to create a new column 'Difference' that subtracts column 'B' from 'A' for each row.

Pandas
import pandas as pd

df = pd.DataFrame({'A': [9, 4], 'B': [3, 7]})
df['Difference'] = df.apply(lambda [1]: [2]['A'] - [2]['B'], axis=1)
print(df)
Drag options to blanks, or click blank then click option'
Arow
Bdf
Cdata
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that is not the lambda argument to access row data.
Not matching the lambda argument name with its usage inside the function.
5fill in blank
hard

Fill all three blanks to create a dictionary with keys as row indices and values as the row values from column 'b' where the value in 'a' is greater than 2.

Pandas
import pandas as pd

df = pd.DataFrame({'a': [1, 3], 'b': [4, 5]})
result = { [1]: row[[2]] for index, row in df.iterrows() if row[[3]] > 2 }
print(result)
Drag options to blanks, or click blank then click option'
A'A'
B'b'
C'a'
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using column names incorrectly as keys.
Mixing up the filter condition column and value column.