我有一个带有字段'进程日期'和另一个字段'有效_date'的数据框架。"有效_date"字段包含日期列表。我要完成的工作是选择最接近提交的"过程日期"中包含的日期的日期。(换句话说,与过去最接近的日期)。例如,在下面的框架中,第一个"过程日期" -4/14/2014在第[0]中应匹配到3/2/2010。
事先感谢您的帮助。
Title Code Process Date Type Title_code
0 40493 4/4/2014 SI 40493
1 40493 4/18/2014 SI 40493
2 40493 5/2/2014 SI 40493
3 40493 5/16/2014 SI 40493
4 40493 5/30/2014 SI 40493
5 40493 6/13/2014 SI 40493
6 10251 10/4/2013 RIP 10251
7 40491 10/18/2013 LD 40491
8 40491 10/18/2013 SI 40491
9 40491 11/1/2013 LD 40491
10 40491 11/1/2013 SI 40491
11 40491 11/15/2013 LD 40491
12 40491 11/15/2013 SI 40491
Effective_date
0 ['3/2/2010', '3/3/2017', '9/3/2016']
1 ['3/2/2010', '3/3/2017', '9/3/2016']
2 ['3/2/2010', '3/3/2017', '9/3/2016']
3 ['3/2/2010', '3/3/2017', '9/3/2016']
4 ['3/2/2010', '3/3/2017', '9/3/2016']
5 ['3/2/2010', '3/3/2017', '9/3/2016']
6 ['9/3/2011', '9/3/2012', '9/3/2013', '9/3/2014...
7 ['9/3/2016', '3/2/2010']
8 ['3/2/2010', '3/3/2017', '9/3/2016']
9 ['9/3/2016', '3/2/2010']
10 ['3/2/2010', '3/3/2017', '9/3/2016']
11 ['9/3/2016', '3/2/2010']
12 ['3/2/2010', '3/3/2017', '9/3/2016']
您可以使用np.searchsorted
查找应插入日期的位置。您的列表未分类,因此需要首先完成。您在数据框架中有一个列表,因此这些都不会特别快。您需要单独搜索每一行,因此我们将使用列表理解:
示例数据:
import pandas as pd
import numpy as np
from random import shuffle
df = pd.DataFrame({'Process Date': pd.date_range('2013-01-01', freq='3M', periods=10)})
l1 = pd.date_range('2012-01-01', freq='96D', periods=13).tolist()
shuffle(l1) #So it isn't ordered
df['Effective_Date']= [l1 for i in range(10)]
代码:
df['Effective_Date'] = df['Effective_Date'].apply(np.sort)
df['Date_Before'] = [l[np.searchsorted(l, date)-1]
for l,date in zip(df['Effective_Date'], df['Process Date'])]
输出:
print(df[['Process Date', 'Date_Before']])
Process Date Date_Before
0 2013-01-31 2013-01-19
1 2013-04-30 2013-04-25
2 2013-07-31 2013-07-30
3 2013-10-31 2013-07-30
4 2014-01-31 2013-11-03
5 2014-04-30 2014-02-07
6 2014-07-31 2014-05-14
7 2014-10-31 2014-08-18
8 2015-01-31 2014-11-22
9 2015-04-30 2015-02-26
给定索引,如果'Process Date'
在'Effective_Date'
中的最早日期之前,这将导致问题(您将使用-1
索引并获取最新日期)。在事实之后解决这一点可能最简单,或者可以在列表理解中添加if-else
。
df.loc[df.Date_Before.gt(df['Process Date']), 'Date_Before'] = pd.NaT