Remove columns starting with numbers

Viewed 147

I have a dataframe with multiple columns starting with a number. For instance,

00am    00pm    02am    03am    10am    10k 11th    12th    13th ... ABC     JOIN
example example example ...       ...        ...       ...     ...  example  example

I would like to remove all the columns that start with a number to have

    ... ABC JOIN
...  example  example

I used str and isdigit

df.loc[:,~df.columns.str.isdigit()]

but the result stills shows columns starting with numbers. Similarly I should exclude columns that contains numbers (I would say that in this case I should use str.contain()).

3 Answers

Use a regular expression to check the column names

df = pd.DataFrame([[1,2,3,4,5]],columns=['0a','0b','0c','0d','e'])

    0a  0b  0c  0d  e
0   1   2   3   4   5


df[df.columns[~df.columns.str.match('^\d')]]

    e
0   5
import re
df[[c for c in df.columns if not re.findall("\d", c[0])]]

'Loc' and 'isdigit' functions can be also used, but not in the way you wanted. You could do it differently:

df.loc[:, [x[0].isdigit() is False for x in df.columns]]

In this case we choose all rows plus columns which start from a digit.

Related