首页 > 解决方案 > 根据具有范围的条件向列添加值

问题描述

我有两个数据集:

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

标签: pythonpandasnumpy

解决方案


推荐阅读