codeninja
codeninja

Reputation: 379

Pandas removing duplicate range of data

Hi all I have the following dataframe:

df1
      WL       WM      WH        WP      
1     low    medium   high   premium
2     26       26      15        14
3     32       32      18        29 
4     41       41      19        42
5     apple    dog     fur      napkins          
6     orange   cat     tesla    earphone
7     NaN      rat     tobias   controller
8     NaN      NaN     phone
9     low      medium  high            
10     1        3       5
11     2        4       6
12    low      medium  high
13     4        8       10
14     5        9       11

Is there a way to remove low + 2 rows such that the output is such:

df1
      WL       WM      WH        WP      
1     low    medium   high   premium
2     26       26      15        14
3     32       32      18        29 
4     41       41      19        42
5     apple    dog     fur      napkins          
6     orange   cat     tesla    earphone
7     NaN      rat     tobias   controller
8     NaN      NaN     phone

Unfortunately the code must be dynamic because I have multiple dataframes and the placement for 'low' is different in each. My initial attempt:

df1 = df1[~df1.iloc[:,0].isin(['LOW'])+2].reset_index(drop=True)

however this is not quite what I am looking for. Any help is appreciated

Upvotes: 1

Views: 36

Answers (1)

jezrael
jezrael

Reputation: 863166

You can use:

#get index values where low
a = df.index[df.iloc[:,0] == 'low']

size = 2
#all index values (without first [1:])
#min is for last rows of df for avoid select non existed values
arr = [np.arange(i, min(i+size+1,len(df)+1)) for i in a[1:]]
idx = np.unique(np.concatenate(arr))
print (idx)
[ 9 10 11 12 13 14]

#remove rows
df = df.drop(idx)
print (df)
       WL      WM      WH          WP
1     low  medium    high     premium
2      26      26      15          14
3      32      32      18          29
4      41      41      19          42
5   apple     dog     fur     napkins
6  orange     cat   tesla    earphone
7     NaN     rat  tobias  controller
8     NaN     NaN   phone         NaN

Upvotes: 1

Related Questions