About Lesson
You can easily modify DataFrames by adding or deleting columns, changing values, or applying transformations.
1. Adding a New Column
To add a new column, you simply assign a list or a scalar value to a new column name.
df['Country'] = ['USA', 'USA', 'USA']
print(df)
2. Modifying Existing Data
You can modify data by referencing specific rows and columns:
df.at[1, 'Age'] = 32 # Modify a specific value
df['Age'] = df['Age'] + 1 # Apply a transformation to an entire column
print(df)
3. Deleting Columns
To delete a column, use drop
:
df = df.drop('Country', axis=1) # axis=1 refers to columns
print(df)
4. Deleting Rows
To delete rows, use drop
with axis=0
(default):
df = df.drop(1, axis=0) # Drop the second row (index 1)
print(df)