I want to delete multiple rows where, df.service == 'harvest' or 'http_2873' or 'red_i', but I'm running a for loop and going through the entire df instead
for _ in df1.service:
i = df1[((df1.service == 'harvest'))].index
df1.drop(i)
I want to delete multiple rows where, df.service == 'harvest' or 'http_2873' or 'red_i', but I'm running a for loop and going through the entire df instead
for _ in df1.service:
i = df1[((df1.service == 'harvest'))].index
df1.drop(i)
You could exclude the rows that contain any of those strings you listed using str.contains, which allows | (or), and returns a boolean. Then you filter your DataFrame with .loc and ~ negation.
:
new = df.loc[~df.Service.str.contains(r'harvest|http_2873|red_i')]
>>> new
Date Customers Location Sales Service
12 05/10/2021 A NSW 12 one
13 03/10/2021 B NSW 10 two
14 01/10/2021 C NSW 33 three
You can also include case=False in str.contains('..',case=False) which disregards upper / lower cases in case you want to.
Use this:
df[~((df['Service'] == 'harvest') | (df['Service'] == 'http_2873') | (df['Service'] == 'red_i'))]
.
df
Date Customers Location Sales Service
0 2021-10-05 A NSW 12 harvest
1 2021-10-03 B NSW 10 http_2873
2 2021-10-01 C NSW 33 red_i
0 2021-10-05 A NSW 12 harvest
1 2021-10-03 B NSW 10 http_2873
2 2021-10-01 C NSW 33 red_i
0 2021-10-05 A NSW 12 harvest
1 2021-10-03 B NSW 10 http_2873
2 2021-10-01 C NSW 33 red_i
0 2021-10-05 A NSW 12 harvest
1 2021-10-03 B NSW 10 http_2873
2 2021-10-01 C NSW 33 red_i
df[~((df['Service'] == 'harvest') | (df['Service'] == 'http_2873') | (df['Service'] == 'red_i'))]
Date Customers Location Sales Service
1 2021-10-03 B NSW 10 hello
2 2021-10-01 C NSW 33 hello1
0 2021-10-05 A NSW 12 hello3
df2 = df[(df['service'] != 'harvest') & (df['service'] != 'http_2873') & (df['service'] != 'red_i')]
Deleting those rows with service which equals harvest or http_2873 or red_i means leaving the rows with service which is not equal to harvest and not equal to http_2873 and not equal to red_i.
You have to assign df to a new DataFrame df2, otherwise you would not get the result you want.