将功能应用于现有的“日期”列

时间:2018-11-05 10:10:35

标签: python pandas function date

我有以下虚构的代码(我的代码很敏感):

df
record_id     date    sick funny    happy
XK2C0001-3  7/10/2018   2   1       1
XK2C0002-1  7/10/2018   2   4       1
XK2C0003-9  7/11/2018   2   4       1
ZT2C0004-7  7/11/2018   2   4       1
XK2C0005-4  7/11/2018   1   1       1
XK2C0001-3  7/10/2018   2   4       1
XK2C0002-1  7/10/2018   2   4       1
XK2C0003-9  7/11/2018   1   4       1
XK2C0004-7  7/11/2018   2   4       1
ZT2C0005-4  7/11/2018   2   4       1


male_gender=df.loc[(df['sick'] == 1) | (df['funny'] == 1) | (df['happy'] == 1)]
male_gender['date'].value_counts().head()
2018-10-02    22
2018-10-03    14
2018-10-05    10
2018-11-01    10
2018-10-22    10
Name: date, dtype: int64

并且我具有以下工作功能来过滤最近7个工作日:

prev_days = [today - timedelta(days=i) for i in range(10)]  
prev_days = [d for d in prev_days if d.weekday() < 5]       
for d in prev_days[:7]:                                     
    print(d)

我的问题是:如何将以上功能应用于数据框列“日期”?我只是想要一个想法,上面的数据是虚构的,您可以举另一个例子。

编辑:我想知道在相对于今天的过去7个工作日中,我有多少男性。

1 个答案:

答案 0 :(得分:2)

df['date']转换为datetime系列,过滤数据框,然后然后使用pd.Series.value_counts

df['date'] = pd.to_datetime(df['date'])

m1 = (df['sick'] == 1) | (df['funny'] == 1) | (df['happy'] == 1)  # custom conditions
m2 = df['date'] >= pd.Timestamp('today') - pd.DateOffset(days=7)  # last 7 days
m3 = ~df['date'].dt.weekday.isin([5, 6])                          # not Sat or Sun

res = df.loc[m1 & m2 & m3, 'date'].value_counts()