Friedrich Franz Friedrich Franz - 1 year ago 95
Python Question

Pandas: Drop Columns that are equal to weekend

I have a probably rather simple question. I have a daily df for 10 years consisting of columns that have data and are named according to the day:

2017-04-07 2017-04-08 2017-04-09
a a a

I now want to drop every column which name, i.e. which day, is equal to a weekend. For example, in the above example only this would remain:


Does anybody know how to do this?

Answer Source

Use weekday + isin for mask with loc and boolean indexing for select all columns which are not (~) weekdays:

print (df)
  2017-04-07 2017-04-08 2017-04-09 2017-04-10
0          a          a          a          a

#if necessary
df.columns = pd.to_datetime(df.columns)

print (~df.columns.weekday.isin([5,6]))
[ True False False  True]

print (df.loc[:, ~df.columns.weekday.isin([5,6])])
  2017-04-07 2017-04-10
0          a          a

Another solution:

df.columns = pd.to_datetime(df.columns)
print (df[df.columns[~df.columns.weekday.isin([5,6])]])
  2017-04-07 2017-04-10
0          a          a

For older verison of pandas use:

print (df[df.columns[~pd.Series(df.columns.weekday).isin([5,6])]])
  2017-04-07 2017-04-10
0          a          a


print (df[df.columns[np.in1d(df.columns.weekday, [5,6])]])
  2017-04-08 2017-04-09
0          a          a
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download