2

我有一个可能相当简单的问题。我有 10 年的每日 df,其中包含有数据并根据日期命名的列:

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

我现在想删除每个名称(即哪一天)等于周末的列。例如,在上面的示例中,仅保留以下内容:

2017-04-07       
   a               

有人知道怎么做这个吗?

4

1 回答 1

2

使用weekday+isin作为掩码,locboolean indexing选择所有不是 ( ~) 工作日的列:

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

另一种解决方案:

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

对于较旧的熊猫版本,请使用:

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
于 2017-06-20T14:44:18.783 回答