首页 > 解决方案 > 使用 pandas 数据框根据日期范围创建新变量并应用条件值

问题描述

这里是 Python 和一般编码的新手,所以这对你们大多数人来说应该是非常基本的。

我基本上用日期时间索引创建了这个数据框。

这是数据框

df = pd.date_range(start='2018-01-01', end='2019-12-31', freq='D')

我现在想在我的 df 中添加一个名为“假期”的新变量,如果日期在 2018 年 6 月 24 日和 2018 年 8 月 24 日之间,则值为 1,如果不在这些日期之间,则值为 0。我该怎么做呢?我创建了一个包含假期范围的变量,但我不确定如何将这两个放在一起,以及在我的数据框中为“假期”创建一个新列。

vacation = pd.date_range(start = '2018-06-24', end='2018-08-24')

提前致谢。

标签: pythonpandasdatetime

解决方案


新的解决方案DataFrame

i = pd.date_range(start='2018-01-01', end='2018-08-26', freq='D')

m = (i > '2018-06-24') & (i < '2018-08-24') 
df = pd.DataFrame({'vacation': m.astype(int)}, index=i)

或者:

df = pd.DataFrame({'vacation':np.where(m, 1, 0)}, index=i)

print (df)
            vacation
2018-01-01         0
2018-01-02         0
2018-01-03         0
2018-01-04         0
2018-01-05         0
             ...
2018-08-22         1
2018-08-23         1
2018-08-24         0
2018-08-25         0
2018-08-26         0

[238 rows x 1 columns]

将新列添加到现有的解决方案DataFrame

通过与forDatetimeIndex链接比较创建掩码并将其转换为整数(to和to )或使用:&bitwise ANDTrue1False0numpy.where

i = pd.date_range(start='2018-01-01', end='2018-08-26', freq='D')
df = pd.DataFrame({'a': 1}, index=i)

m = (df.index > '2018-06-24') & (df.index < '2018-08-24') 

df['vacation'] = m.astype(int)
#alternative
#df['vacation'] = np.where(m, 1, 0)
print (df)
            a  vacation
2018-01-01  1         0
2018-01-02  1         0
2018-01-03  1         0
2018-01-04  1         0
2018-01-05  1         0
       ..       ...
2018-08-22  1         1
2018-08-23  1         1
2018-08-24  1         0
2018-08-25  1         0
2018-08-26  1         0

[238 rows x 2 columns]

另一个具有DatetimeIndexDataFrame.loc- 差异的解决方案1包括2018-06-24边缘2018-08-24值:

df['vacation'] = 0
df.loc['2018-06-24':'2018-08-24'] = 1
print (df)
           a  vacation
2018-01-01  1         0
2018-01-02  1         0
2018-01-03  1         0
2018-01-04  1         0
2018-01-05  1         0
       ..       ...
2018-08-22  1         1
2018-08-23  1         1
2018-08-24  1         1
2018-08-25  1         0
2018-08-26  1         0

[238 rows x 2 columns]

推荐阅读