python - 使用 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')
提前致谢。
解决方案
新的解决方案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 AND
True
1
False
0
numpy.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]
另一个具有DatetimeIndex
和DataFrame.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]
推荐阅读
- git - Visual Studio 上的 GIT 远程扩展 - 显示大量未知更改
- python - AttributeError:“str”对象没有属性“weekday”
- ssl - 使用 Elastic Beanstalk 设置 SSL:如何修复 ERR_CERT_COMMON_NAME_INVALID?
- javascript - 使用 javascript 将 css 样式转换为内联样式,保持样式单元
- angular - 如何从 Angular 9 中的 url 中删除哈希,并将浏览器中的 url 更新为当前 url
- drake - 从源代码构建和使用 pydrake
- spring-boot - Kafka Consumer 指标在从 Spring Boot 2.2.2 升级到 2.3.0 后消失
- c++ - 继承默认构造函数,矛盾吗?
- php - 如何修复运行 PHP 和 Pthreads 的 Codeigniter 应用程序中的内存泄漏?致命错误:已用完 2147483648 字节的允许内存大小
- python - MEDIA_URL 在 Django 模板中不起作用