[英]How to use np.Vectorize() with Pandas function?
我有 function 以 Pandas DataFrame 格式運行。 它適用於pandas.apply()
但不適用於np.Vectorize()
。 在下面找到 function:
def AMTTL(inputData, amortization = []):
rate = inputData['EIR']
payment = inputData['INSTALMENT']
amount = inputData['OUTSTANDING']
amortization = [amount]
if amount - payment <= 0:
return amortization
else:
while amount > 0:
amount = BALTL(rate, payment, amount)
if amount <= 0:
continue
amortization.append(amount)
return amortization
inputData
以 Pandas DataFrame 格式接收 inputData。 EIR
、 INSTALMENT
和OUTSTANDING
是列名。 這個 function 與pandas.apply()
配合得很好
data.apply(AMTTL, axis = 1)
但是,我嘗試使用np.Vectorize()
。 它不適用於以下代碼:
vfunc = np.vectorize(AMTTL)
vfunc(data)
它得到像'Timestamp' object is not subscriptable
這樣的錯誤。 因此,我嘗試刪除其他未使用的列,但仍然出現另一個錯誤,例如invalid index to scalar variable.
我不確定如何將pandas.apply()
調整為np.Vectorize()
。 有什么建議嗎? 先感謝您。
np.vectorize
只不過是應用於數組所有元素的map
function - 這意味着您無法區分 function 中的列。 它不知道EIR
或INSTALMENT
之類的列名。 因此,您當前對 numpy 的實現將不起作用。
從文檔:
The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.
提供矢量化 function 主要是為了方便,而不是為了性能。 該實現本質上是一個 for 循環。
根據您的問題,您應該嘗試np.apply_along_axis
,您可以在其中引用不同的列及其索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.