我有两个数据框。
dfB = pd.DataFrame({'Initials':['AA','BB','CC','DD','EE','FF'],
'Zone': ['Red','Red','Red','Yellow','Yellow','Yellow'],
'Start Date':['1998-01-01','1999-01-01','2005-01-01','2000-01-01','2002-01-01','2010-01-01'],
'End Date': ['1998-12-31','2004-12-31','2020-04-22','2001-12-31','2009-12-31','2020-04-22']})
dfA = pd.DataFrame({'Initials':['GG','HH','II','JJ','KK','LL'],
'Zone': ['Red','Yellow','Red','Yellow','Red','Yellow'],
'Date': ['2011-02-11','2004-11-03','2010- 04-12','2007-12-03','2008-12-01','2019-06-29']})
我想在dfA中添加一列新的数据,从该数据框中提取日期,然后在dfB中找到它在 "开始 "和 "结束 "日期列之间的位置。 这些区域也必须匹配。 然后,它将从dfB中的那行中提取Initials,并将其放入dfA中的新列中。
我正在尝试用这段代码来做。
dfB['Start Date'] = dfB['Start Date'].apply(lambda x: time.strptime(x, "%Y-%m-%d"))
dfB['End Date'] = dfB['End Date'].apply(lambda x: time.strptime(x, "%Y-%m-%d"))
dfA['Date'] = dfA['Date'].apply(lambda x: time.strptime(x, "%Y-%m-%d"))
for i,row in dfA.iterrows():
a = row['Zone']
dfC = dfB[dfB['Zone']==a]
date = row['Date']
dfA['New'] = dfC.loc[(dfC['Start Date'] < date) & (dfC['End Date'] > date),['Initials']]
我做了date.time函数 以确保我的日期能够被比较 我不确定这是否有必要,但觉得无伤大雅。
然后,我对每一行进行了iterrated,根据区域做了一个过滤的数据框(区域必须匹配),然后试图根据日期的位置找到新的首字母。
问题是,我的结果都是NaN。 正如你所看到的,日期 应 搭配。 GG应该配CC,HH应该配EE等等。不知道我在这里遗漏了什么?
这样的东西可以用。
In [2247]: d = pd.merge(dfA, dfB, on='Zone')
In [2264]: r = d[d.Date.between(d['Start Date'], d['End Date'])]
In [2279]: dfA['new_initials'] = pd.merge(dfA, r[['Initials_x','Initials_y']], left_on='Initials', right_on=['Initials_x'])['Initials_y']
In [2280]: dfA
Out[2280]:
Initials Zone Date new_initials
0 GG Red 2011-02-11 CC
1 HH Yellow 2004-11-03 EE
2 II Red 2010-04-12 CC
3 JJ Yellow 2007-12-03 EE
4 KK Red 2008-12-01 CC
5 LL Yellow 2019-06-29 FF