Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – Drop / Keep rows based on column values using column location instead of column names

Drop / Keep rows based on column values using column location instaed of column names.

data = {"product_name":["Keyboard","Mouse", "Monitor", "CPU","CPU", "Speakers"],
        "Unit_Price":[500,200, 5000.235, 10000.550, 10000.550, 250.50],
        "No_Of_Units":[5,5, 10, 20, 20, 8],
        "Available_Quantity":[5,6,10,1,3,2],
        "Available_Since_Date":['11/5/2021', '4/23/2021', '08/21/2021','09/18/2021','09/18/2021','01/05/2021']
       }
   

Drop / Keep rows with ‘CPU’ in column ‘product_name’ but without using column name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use iloc for selection of the column by position, then boolean indexing:

# select the first column and check if the items contain "CPU"
m = df.iloc[:, 0].str.contains('CPU')
# for strict equality
# m = df.iloc[:, 0].str.eq('CPU')


# keep CPU
df_keep = df[m]

# drop CPU
df_drop = df[~m]

Output:

# df_keep
  product_name  Unit_Price  No_Of_Units  Available_Quantity Available_Since_Date
3          CPU    10000.55           20                   1           09/18/2021
4          CPU    10000.55           20                   3           09/18/2021

# df_drop
  product_name  Unit_Price  No_Of_Units  Available_Quantity Available_Since_Date
0     Keyboard     500.000            5                   5            11/5/2021
1        Mouse     200.000            5                   6            4/23/2021
2      Monitor    5000.235           10                  10           08/21/2021
5     Speakers     250.500            8                   2           01/05/2021
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading