Recall & Review
beginner
How do you add a new column to a pandas DataFrame with a fixed value?
You can add a new column by assigning a value to a new column name like this: <br>
df['new_column'] = 10<br>This sets the value 10 for all rows in the new column.Click to reveal answer
beginner
What is the syntax to create a new column based on existing columns in pandas?
You can create a new column by performing operations on existing columns:<br>
df['new_col'] = df['col1'] + df['col2']<br>This adds values from 'col1' and 'col2' row-wise.Click to reveal answer
intermediate
How can you create a new column using a function applied to each row in pandas?
Use the
apply() method with axis=1 to apply a function row-wise:<br>df['new_col'] = df.apply(lambda row: row['col1'] * 2, axis=1)Click to reveal answer
beginner
What happens if you assign a list of values to a new column in pandas?
If the list length matches the number of rows, pandas assigns each list item to the corresponding row in the new column.<br>Example:<br>
df['new_col'] = [1, 2, 3] for a DataFrame with 3 rows.Click to reveal answer
intermediate
How do you create a new column conditionally in pandas?
Use
np.where() or boolean indexing:<br>df['new_col'] = np.where(df['col'] > 5, 'High', 'Low')<br>This sets 'High' if value > 5, else 'Low'.Click to reveal answer
Which of the following adds a new column 'age_plus_10' that adds 10 to the 'age' column?
✗ Incorrect
Adding 10 to the 'age' column creates a new column with each age increased by 10.
What does this code do? <br>df['new_col'] = df.apply(lambda row: row['a'] * 2, axis=1)
✗ Incorrect
The apply function with axis=1 applies the lambda to each row, doubling the 'a' value.
If you assign a list shorter than the DataFrame rows to a new column, what happens?
✗ Incorrect
The list length must match the number of rows; otherwise, pandas raises a ValueError.
How to create a new column 'status' that is 'Adult' if 'age' >= 18, else 'Minor'?
✗ Incorrect
np.where applies the condition element-wise to create the new column.
Which method is best to create a new column based on multiple existing columns with complex logic?
✗ Incorrect
df.apply() allows applying complex logic row-wise using a custom function.
Explain how to add a new column to a pandas DataFrame with values based on existing columns.
Think about using df['new_col'] = df['col1'] + df['col2'] or apply with lambda.
You got /4 concepts.
Describe how to create a new column conditionally in pandas.
Use np.where(condition, value_if_true, value_if_false).
You got /4 concepts.