Creating new columns in Pandas - Performance & Efficiency
When we add new columns to a pandas DataFrame, it takes some time to process. We want to understand how this time changes as the DataFrame gets bigger.
The question is: How does the time to create new columns grow when the number of rows increases?
Analyze the time complexity of the following code snippet.
import pandas as pd
n = 10 # Example value for n
df = pd.DataFrame({
'A': range(n),
'B': range(n, 2*n)
})
df['C'] = df['A'] + df['B']
This code creates a DataFrame with two columns and then adds a new column 'C' by adding columns 'A' and 'B' element-wise.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding values from columns 'A' and 'B' for each row.
- How many times: Once for each row in the DataFrame (n times).
As the number of rows grows, the time to add the new column grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the rows doubles the work needed to create the new column.
Time Complexity: O(n)
This means the time to create a new column grows linearly with the number of rows in the DataFrame.
[X] Wrong: "Creating a new column is instant and does not depend on DataFrame size."
[OK] Correct: Each row must be processed to compute the new column values, so time grows with the number of rows.
Understanding how data size affects operations like adding columns helps you write efficient code and explain your choices clearly in real projects.
"What if we create the new column using a constant value instead of adding two columns? How would the time complexity change?"
Practice
age + 10 to a DataFrame df that adds 10 to the existing age column?Solution
Step 1: Understand how to create a new column in pandas
In pandas, new columns are created by assigning a value todf['new_column_name'].Step 2: Apply the addition operation to the existing column
Adding 10 to theagecolumn is done bydf['age'] + 10. Assigning this todf['age + 10']creates the new column.Final Answer:
df['age + 10'] = df['age'] + 10 -> Option BQuick Check:
New column assignment = df['age + 10'] = df['age'] + 10 [OK]
- Using double equals (==) instead of single equals (=) for assignment
- Trying to use a method like add_column which doesn't exist
- Using dot notation for new columns with spaces or special characters
full_name by combining first_name and last_name columns with a space in between in DataFrame df?Solution
Step 1: Combine string columns with + operator
In pandas, string columns can be combined using the + operator. To add a space, include ' ' between them.Step 2: Assign the combined string to a new column
Assign the result todf['full_name']to create the new column.Final Answer:
df['full_name'] = df['first_name'] + ' ' + df['last_name'] -> Option AQuick Check:
String concat with + = df['full_name'] = df['first_name'] + ' ' + df['last_name'] [OK]
- Using append or join methods which don't work on pandas Series
- Using & operator which is for bitwise operations
- Forgetting to add space between names
df below:price quantity 0 100 2 1 150 3 2 200 1
What will be the output of this code?
df['total'] = df['price'] * df['quantity'] df['total']
Solution
Step 1: Multiply price and quantity element-wise
Multiply each row's price by quantity: 100*2=200, 150*3=450, 200*1=200.Step 2: Assign result to new column and output it
The new column 'total' will have values [200, 450, 200]. Printing df['total'] shows this list.Final Answer:
[200, 450, 200] -> Option AQuick Check:
Element-wise multiply = [200, 450, 200] [OK]
- Adding instead of multiplying columns
- Confusing row-wise with column-wise operations
- Expecting a scalar instead of a Series output
discounted_price by subtracting 10 from price in DataFrame df?
df.discounted_price = df['price'] - 10
Solution
Step 1: Understand dot notation for DataFrame columns
Dot notationdf.col = valueworks to create new columns only if 'col' is a valid Python identifier (no spaces, no special characters).Step 2: Check the column name 'discounted_price'
'discounted_price' consists of letters and underscores, which is valid. Therefore, the code creates the column correctly.Final Answer:
It will create the column correctly. -> Option DQuick Check:
Dot notation works for valid identifiers [OK]
- Thinking dot notation fails for valid column names
- Confusing DataFrame column assignment with local variable creation
- Believing underscores invalidate column names for dot notation
df with columns score and max_score. You want to create a new column percentage that shows the score as a percentage of max_score, but if max_score is zero, set percentage to None. Which code correctly does this?Solution
Step 1: Use row-wise function to handle zero max_score
Usingdf.applywith a lambda lets us check each row and apply the condition: if max_score is zero, return None; else calculate percentage.Step 2: Assign the result to new column 'percentage'
The lambda returns the correct value per row, andaxis=1ensures row-wise operation.Final Answer:
df['percentage'] = df.apply(lambda row: row['score'] / row['max_score'] * 100 if row['max_score'] != 0 else None, axis=1) -> Option CQuick Check:
Use apply with condition for safe division [OK]
- Replacing zero with None in Series causes errors
- Using chained indexing which raises warnings
- Not handling division by zero properly
Ready to prove it?
Pass the test and this pattern moves unknown
