Tidyverse Py Charm
Tidyverse Py Charm

Reputation: 1

How can I drop column using combination of string and integer?

I have many columns name with string with (t+1) (t+2) .... (t+54) In pictured attached, How can I drop just only columns "lemon(t+1),....,lemon(t+30), not lemon(t-1)

Thanks

enter image description here

Upvotes: 0

Views: 42

Answers (2)

Umar.H
Umar.H

Reputation: 23099

using a list comprehension -

df.drop([f"lemon(t-{i})" for i in range(1,31)],axis=1)

Upvotes: 1

shmakovpn
shmakovpn

Reputation: 831

See comments in code

cols = df.columns  # get columns of the dataframe
# filter the list of columns by removeing items from 'lemon(t+1)' to 'lemon(t+30)'
cols2 = filter(lambda x: not (x.startswith('lemon(t+') and x[8:-1]>0 and x[8:-1]<31) )
df_result = df[cols2]  # create needed dataframe

Upvotes: 1

Related Questions