Class 12 Remove Columns and rows in dataframe


 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 DataFrame
data = {
'Year': [2020, 2021, 2022, 2023],
'Subject': ['Math', 'Physics', 'Chemistry', 'Biology'],
'Question': [
'Q1',
'Q2',
'Q3',
'Q4'
]
}
df = pd.DataFrame(data)
# Remove a single column
df = df.drop('Question', axis=1)
# Remove multiple columns
#df = df.drop(['Year', 'Subject'], axis=1)
print(df)

Remove Single Columns


Remove 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 DataFrame
df = pd.DataFrame(data)
# 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)





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 DataFrame
df = pd.DataFrame(data)
# Remove a column in-place
df.drop('Question', axis=1, inplace=True)
# Remove a row in-place
df.drop(1, axis=0, inplace=True)
print(df)

Post a Comment

0 Comments