问题描述
我有一个可以很好地处理单个值的函数,但是当我将它与 pandas series.apply() 一起使用时,它给出了一个溢出错误。
from __future__ import division
import pandas as pd
import numpy as np
birthdays = pd.DataFrame(np.empty([365,2]), columns = ['k','probability'], index = range(1,366))
birthdays['k'] = birthdays.index
我做了一个功能:
def probability_of_shared_bday(k):
end_point = 366 - k
numerator = 1
for i in range(end_point, 366):
numerator = numerator*i
denominator = 365**k
probability_of_no_match = (1 - numerator/denominator)
return probability_of_no_match
当我用单个整数尝试这个时,它工作正常:
probability_of_shared_bday(1)
0.0
probability_of_shared_bday(100)
0.9999996927510721
但是当我尝试将这个函数与 apply 一起使用时:
birthdays['probability'] = birthdays['k'].apply(probability_of_shared_bday, convert_dtype=False)
溢出错误:整数除法结果对于浮点数太大
无论convert_dtype
是 True 还是 False,都会发生这种情况。
检查birthdays['k'].dtypes
我得到birthdays['k'].dtypes
dtype('int64')
1楼
我不确定为什么你的apply
有这个问题,但你不应该像一开始那样编写函数。
这是一个避免将两个巨大数字相除的建议:
def probability_of_shared_bday(k):
end_point = 366 - k
ratio = 1
for i in range(end_point, 366):
ratio *= i / 365
probability_of_no_match = (1 - ratio)
return probability_of_no_match
问题就迎刃而解了!