python - 根据具有范围的条件向列添加值
问题描述
我有两个数据集:
Dict
Number_ID | 价格 | 开始日期 | 结束日期 |
---|---|---|---|
1 | 3.49 | 20200101 | 20991231 |
2 | 0.25 | 20200101 | 20200502 |
2 | 0.49 | 20200503 | 20200509 |
3 | 0.13 | 20200401 | 20200403 |
3 | 0.15 | 20200404 | 20991231 |
和
Sales_List
Number_ID | 销售日期 |
---|---|
1 | 20200103 |
2 | 20200431 |
2 | 20200505 |
3 | 20200402 |
3 | 20200408 |
我的目标是使用 Dict 表中的数据,并在以下条件下从 Dict['Price'] 为 Sales_List['Price'] 设置正确的值:
Number_ID is the same
Sales['Date of Sales'] is between Dict['StartDate'] and Dict['EndDate']
我试过下面的代码,但我有一些错误:
import pandas as pd
import numpy as pd
Sales_List['Price'] = np.where((Sales_List['Number_ID'] == Dict['Number_ID']) &
(Sales_List['Date of Sale'] >= Dict['StartDate']) &
(Sales_List['Date of Sale'] < Dict['EndDate']),
Dict['Price'],'')
我也尝试过以下代码:
Sales_List = Sales.merge(Dict, how='left', on='Number_ID').reset_index()
Sales_List['Value'] = np.where((Sales_List['Date of Sale'] >= Dict['StartDate']) &
(Sales_List['Date of Sale'] < Dict['EndDate']),1,0)
Sales_List = Sales_List[Sales_List['Value'] = 1]
但是在第二个示例中,此合并分配了太多内存并使其崩溃。(Sales_List 超过 30M 行,Dict 有 12k 行)
MemoryError: Unable to allocate 7.15 GiB for an array with shape (5, 191907116) and data type int64
你们中的任何人都知道如何以更有效的方式(比第二个示例)在 python 中做类似的事情吗?
输出应如下所示:
Number_ID | 销售日期 | 价格 |
---|---|---|
1 | 20200103 | 3.49 |
2 | 20200431 | 0.25 |
2 | 20200505 | 0.49 |
3 | 20200402 | 0.13 |
3 | 20200408 | 0.15 |
3 | 20200401 | 0.13 |
3 | 20200409 | 0.15 |
2 | 20200509 | 0.49 |
2 | 20200508 | 0.49 |
解决方案
推荐阅读
- set - 有没有可以处理巨大集合的集合协调算法?
- websphere-liberty - 自由:devc:
不被尊重 - html - 如何将媒体查询应用于带有图像的卡片
- bash - 为什么`avar=7; exec $avar< <(ls)` 让我的 shell 崩溃
- python - 如何在主循环中为 aclass 的每个元素调用一个函数?
- javascript - 如何为多个父母的孩子添加课程?
- kubernetes - Kubernetes 资源文档中的 M 和 Mi 有什么区别?
- javascript - 函数内部循环迭代之间的延迟
- kubernetes - Airflow 2.0.1:Pod 模板覆盖无法按预期为 KubernetesExecutor 工作
- android - 处理手势时抛出 NoSuchMethodError