Concept Flow - Adding and removing columns
Start with DataFrame
Add Column
Check DataFrame
Remove Column
Check DataFrame
End
Start with a DataFrame, add a new column, check the result, then remove a column and check again.
import pandas as pd df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df['C'] = df['A'] + df['B'] df = df.drop('B', axis=1) print(df)
| Step | Action | DataFrame Columns | DataFrame Content | Output |
|---|---|---|---|---|
| 1 | Create DataFrame | ['A', 'B'] | [[1, 3], [2, 4]] | Initial DataFrame with columns A and B |
| 2 | Add column 'C' as A+B | ['A', 'B', 'C'] | [[1, 3, 4], [2, 4, 6]] | Column C added with sums |
| 3 | Remove column 'B' | ['A', 'C'] | [[1, 4], [2, 6]] | Column B removed |
| 4 | Print DataFrame | ['A', 'C'] | [[1, 4], [2, 6]] | Printed final DataFrame |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| df.columns.tolist() | N/A | ['A', 'B'] | ['A', 'B', 'C'] | ['A', 'C'] | ['A', 'C'] |
| df.values.tolist() | N/A | [[1, 3], [2, 4]] | [[1, 3, 4], [2, 4, 6]] | [[1, 4], [2, 6]] | [[1, 4], [2, 6]] |
Adding and removing columns in pandas:
- Add column: df['new_col'] = values
- Remove column: df = df.drop('col_name', axis=1)
- axis=1 means column, axis=0 means row
- Changes update DataFrame structure
- Use print(df) to see changes'age' with all values set to 30 in a pandas DataFrame df?df['column_name'].df['age'] = 30 adds a new column 'age' with all values set to 30.'salary' from a pandas DataFrame df?drop() with axis=1 to specify columns.df.drop('salary', axis=1) removes the 'salary' column from the DataFrame.df below:name score 0 Amy 90 1 Bob 80 2 Cara 85
df['passed'] = df['score'] >= 85 print(df)
df['score'] >= 85 creates a boolean series: True where score is 85 or more, False otherwise.df['passed'] = ... adds this boolean series as a new column.'height' from DataFrame df?
df.drop('height')drop() removes rows. To remove columns, you must specify axis=1.axis=1, so it tries to remove a row named 'height', causing an error if no such row exists.df with columns ['A', 'B', 'C']. You want to create a new column 'D' which is the sum of 'A' and 'B', then remove column 'C'. Which code correctly does this in one step?assign() allows adding a new column in a chainable way without modifying df inplace.drop() chained after assign()drop('C', axis=1) removes column 'C' and returns the modified DataFrame.df updates the DataFrame correctly in one step.Pass the test and this pattern moves unknown