To remove columns and rows in a DataFrame using the Pandas library in Python, you can use the drop method. Here are the steps and examples for each:
Removing Columns
To remove one or more columns from a DataFrame, use the drop method with the axis parameter set to 1 (or columns).
Example:
import pandas as pd
# Sample DataFramedata = {    'Year': [2020, 2021, 2022, 2023],    'Subject': ['Math', 'Physics', 'Chemistry', 'Biology'],    'Question': [        'Q1',        'Q2',        'Q3',        'Q4'    ]}df = pd.DataFrame(data)# Remove a single columndf = df.drop('Question', axis=1)# Remove multiple columns#df = df.drop(['Year', 'Subject'], axis=1)print(df)
Remove Single ColumnsRemove Multiple Columns
Removing Rows
To remove one or more rows from a DataFrame, use the drop method with the axis parameter set to 0 (or index).
Example:
# Sample DataFramedf = pd.DataFrame(data)# Remove a single row by indexdf = df.drop(1, axis=0)# Remove multiple rows by indexdf = df.drop([0, 2], axis=0)print(df)
Single Row
import pandas as pd
# Sample DataFrame
data = {
    'Year': [2020, 2021, 2022, 2023],
    'Subject': ['Math', 'Physics', 'Chemistry', 'Biology'],
    'Question': [
        'Q1',
        'Q2',
        'Q3',
        'Q4'
    ]
}
df = pd.DataFrame(data)
# print DataFrame
print(df,"\n")
# Remove a single row by index
df = df.drop(1, axis=0)
# Remove multiple rows by index
#df = df.drop([0, 2], axis=0)
print(df)
Removing Multiple Rows
import pandas as pd
# Sample DataFrame
data = {
    'Year': [2020, 2021, 2022, 2023],
    'Subject': ['Math', 'Physics', 'Chemistry', 'Biology'],
    'Question': [
        'Q1',
        'Q2',
        'Q3',
        'Q4'
    ]
}
df = pd.DataFrame(data)
# print DataFrame
print(df,"\n")
# Remove a single row by index
#df = df.drop(1, axis=0)
# Remove multiple rows by index
df = df.drop([0, 2], axis=0)
print(df)
Removing Rows/Columns In-Place
To make changes directly to the original DataFrame without creating a new one, use the inplace parameter set to True.
Example:
# Sample DataFramedf = pd.DataFrame(data)# Remove a column in-placedf.drop('Question', axis=1, inplace=True)# Remove a row in-placedf.drop(1, axis=0, inplace=True)print(df)

.png)

0 Comments
Please do note create link post in comment section