Concept Flow - Creating new columns
Start with DataFrame
Define new column values
Assign new column to DataFrame
DataFrame updated with new column
End
We start with a DataFrame, define values for a new column, assign it, and update the DataFrame.
import pandas as pd df = pd.DataFrame({'A': [1, 2, 3]}) df['B'] = df['A'] * 2 print(df)
| Step | Action | DataFrame State | New Column 'B' Values |
|---|---|---|---|
| 1 | Create DataFrame with column 'A' | {'A': [1, 2, 3]} | N/A |
| 2 | Calculate new column 'B' as df['A'] * 2 | Same as step 1 | [2, 4, 6] |
| 3 | Assign new column 'B' to DataFrame | {'A': [1, 2, 3], 'B': [2, 4, 6]} | [2, 4, 6] |
| 4 | Print DataFrame | Displays both columns | [2, 4, 6] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| df | undefined | {'A': [1, 2, 3]} | {'A': [1, 2, 3]} | {'A': [1, 2, 3], 'B': [2, 4, 6]} | {'A': [1, 2, 3], 'B': [2, 4, 6]} |
| df['B'] | undefined | undefined | [2, 4, 6] | [2, 4, 6] | [2, 4, 6] |
Creating new columns in pandas: - Use df['new_col'] = values - Values can be Series, list, or calculations - Length of values must match DataFrame rows - New column appears after assignment - Useful for adding derived data
age + 10 to a DataFrame df that adds 10 to the existing age column?df['new_column_name'].age column is done by df['age'] + 10. Assigning this to df['age + 10'] creates the new column.full_name by combining first_name and last_name columns with a space in between in DataFrame df?df['full_name'] to create the new column.df below:price quantity 0 100 2 1 150 3 2 200 1
df['total'] = df['price'] * df['quantity'] df['total']
discounted_price by subtracting 10 from price in DataFrame df?
df.discounted_price = df['price'] - 10
df.col = value works to create new columns only if 'col' is a valid Python identifier (no spaces, no special characters).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?df.apply with a lambda lets us check each row and apply the condition: if max_score is zero, return None; else calculate percentage.axis=1 ensures row-wise operation.Pass the test and this pattern moves unknown