Drop Column from dataframe with condition


Problem Statement:
You have a DataFrame representing student grades in a class. The DataFrame looks like this:

python

Copy code

import pandas as pd


# Create a sample DataFrame

data = {

    'Student': ['Alice', 'Bob', 'Charlie', 'David'],

    'Math': [85, 90, 78, 88],

    'English': [92, 80, 85, 90],

    'Science': [88, 79, 93, 85]

}

df = pd.DataFrame(data)


The DataFrame df is: OUTPUT

  Student  Math  English  Science

0    Alice    85       92        88

1      Bob    90       80        79

2  Charlie    78       85        93

3    David    88       90        85


Question:

  1. Drop the row where Student is 'Charlie'.

  2. Drop the column 'Science'.



Solutions:

  1. Dropping a Row with condition:

To drop a row where the Student is 'Charlie', you need to identify the index of that row. You can use the drop method in combination with boolean indexing to achieve this:

python

Copy code

# Drop the row where Student is 'Charlie'

d=df[df["Student"]=="Charlie"] print(d) df=df.drop(d.index) print(df)


After this operation, the DataFrame will look like:

  Student  Math  English  Science

0    Alice    85       92        88

1      Bob    90       80        79

3    David    88       90        85






  1. Dropping a Column:

To drop the 'Science' column, use the drop method with the axis parameter set to 1 (since columns are axis 1):

# Drop the column 'Science'

df = df.drop('Science', axis=1)

After this operation, the DataFrame will look like:

  Student  Math  English

0    Alice    85       92

1      Bob    90       80

3    David    88       90

Summary:

  • Use boolean indexing to drop rows based on a condition.

  • Use drop with axis=1 to remove columns.







Post a Comment

0 Comments