2017-07-06 78 views
1

目标:对于在接下来的9个月内具有日期的特定列中的单元格,将新列添加到Master,选择“Yes”,日期即将到来,或者“No”,因为日期不是接下来。使用熊猫,添加timedelta到主数据框中的新行?

我是熊猫新手,所以任何帮助都会很棒。我有一个数据框称为“Master”,因为我将所有内容添加到数据框中,然后导出到Excel电子表格。使用下面的代码,我为日期创建了一个新的数据框,并试图说“如果单元格处于日期状态,请在新列中输入”是“。

我怀疑我的问题是,我试图把熊猫当作数组来处理,但是它实际上做的是在创建一个新的数据框时创建全新的索引并且不保留它如何映射到主。我的理解是否正确?如果是这样,我怎样才能以更优雅的方式实现我的目标?

def mess_with_time(Master): 
    now = datetime.datetime.now() 
    nine_months_in_the_future = str(datetime.datetime.today() + relativedelta(months=+8)) 
    just_future_month=int(nine_months_in_the_future[5:7]) 
    just_future_year=int(nine_months_in_the_future[0:4]) 

    dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))] 
Master['Contract End date coming up?'] = np.where(dates, 'Yes', 'No') #this breaks with 
the error 'Length of values does not match length of index' 

def Create_Master(file): 
    df = pd.ExcelFile('{}.xlsx'.format(file)) 

    Master = df.parse('Main').fillna(0) 

回答

0

我试试您的解决方案改写为大熊猫:

首先是可能使用DateOffset然后between创建布尔面膜:

now = pd.datetime.now() 
months9 = now + pd.offsets.DateOffset(months=8) 
print (months9) 
2018-03-06 15:07:52.850238 

rng = pd.date_range('2017-04-03', periods=10, freq='3M') 
Master = pd.DataFrame({'Contract End Date': rng, 'a': range(10)}) 

dates_mask = Master['Contract End Date'].between(now, months9) 
Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No') 
print (Master) 
    Contract End Date a Contract End date coming up? 
0  2017-04-30 0       No 
1  2017-07-31 1       Yes 
2  2017-10-31 2       Yes 
3  2018-01-31 3       Yes 
4  2018-04-30 4       No 
5  2018-07-31 5       No 
6  2018-10-31 6       No 
7  2019-01-31 7       No 
8  2019-04-30 8       No 
9  2019-07-31 9       No 

看来你需要改变boolean indexingMaster[boolean_condition]boolean condition只:

dates = Master[(Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month))] 

到:

dates_mask = (Master['Contract End Date'] > '{}-{}-1'.format(now.year,now.month)) & (Master['Contract End Date'] <= '{}-{}-20'.format(just_future_year, just_future_month)) 

Master['Contract End date coming up?'] = np.where(dates_mask, 'Yes', 'No')