2016-07-29 51 views
3

我想計算兩次之間的工作日,兩者均包含空值,後面跟計算工作日相關的this question。我已經發現,使用蒙版設置值的方式並不像預期的那樣。使用掩碼設置numpy ndarray的值

我使用的是python 2.7.11,熊貓0.18.1和numpy 1.11.0。我稍微修改代碼:

import datetime 
import numpy as np 
import pandas as pd 

def business_date_diff(start, end): 
    mask = pd.notnull(start) & pd.notnull(end) 
    start = start[mask] 
    end = end[mask] 
    start = start.values.astype('datetime64[D]') 
    end = end.values.astype('datetime64[D]') 
    result = np.empty(len(mask), dtype=float) 
    result[mask] = np.busday_count(start, end) 
    result[~mask] = np.nan 
    return result 

不幸的是,這並沒有返回預期工作日的差異(而不是我得到了一些非常接近0的花車)。當我檢查np.busday_count(start, end)時,結果看起來正確。

print start[0:5] 
print end[0:5] 
print np.busday_count(start, end)[0:5] 

# ['2016-07-04' '2016-07-04' '2016-07-04' '2016-07-04' '2016-07-04'] 
# ['2016-07-05' '2016-07-05' '2016-07-05' '2016-07-06' '2016-07-06'] 
# [1 1 1 2 2] 

但是當我檢查值results結果沒有意義:

... 
result = np.empty(len(mask), dtype=float) 
result[mask] = np.busday_count(start, end) 
result[~mask] = np.nan 
print result 

# [   nan    nan 1.43700866e-210 1.45159738e-210 
# 1.45159738e-210 1.45159738e-210 1.45159738e-210 1.46618609e-210 
# 1.45159738e-210 1.64491834e-210 1.45159738e-210 1.43700866e-210 
# 1.43700866e-210 1.43700866e-210 1.43700866e-210 1.45159738e-210 
# 1.43700866e-210 1.43700866e-210 1.43700866e-210 1.43700866e-210 

我在做什麼錯?

+1

這是面罩有問題嗎? 'mask = pd.notnull(start)&pd.notnull(start)' 不知道你爲什麼使用'pd.notnull(start)'兩次,所以可能是一個bug。 – benten

+0

啊!不幸的是,這是一個轉錄錯字,而不是我正在測試的代碼中的錯字。儘管如此。 –

+0

如何創建'start'和'end'?我嘗試了你正在嘗試做的事情,它似乎對我有用。 –

回答

1

你的問題是,對於你的numpy版本,你不能使用布爾數組作爲數組的索引。只需使用np.where(mask==True)而不是掩碼,而使用np.where(mask==False)而不是〜掩碼,它將按需要工作。