0
$\begingroup$

I have a simple dataframe df2 that consist of indices and one column of values. I want to fit this dataframe to a poisson distribution. Below is the code I am using:

import numpy as np
from scipy.optimize import curve_fit    
data=df2.values
bins=df2.index
def poisson(k, lamb):
    return (lamb^k/ np.math.factorial(k)) * np.exp(-lamb)

params, cov =  curve_fit(poisson, np.array(bins.tolist()), data.flatten())

I get the following error:

TypeError: only size-1 arrays can be converted to Python scalars

$\endgroup$
0
$\begingroup$

I think the cause of the error is the np.math.factorial(k) function call, since curve_fit passes a numpy array as the first parameter to the poisson function, and if you try to run the code

np.math.factorial(np.array([1, 2, 3]))

You'll get the error

TypeError: only size-1 arrays can be converted to Python scalars

Try using scipy.special.factorial since it accepts a numpy array as input instead of only accepting scalers.

Thus, just change your poisson function to

def poisson(k, lamb):
    return (lamb**k/ scipy.special.factorial(k)) * np.exp(-lamb)

Hope this helps

EDIT: Also I fixed the ^ to ** since that's how you use the exponential operator in python.

$\endgroup$
2
  • $\begingroup$ Thanks for your comment. I actually tried factorial from scipy but it gave me the below error, that's why I switched numpy: "TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''" $\endgroup$ – HaneenSu May 5 '20 at 9:57
  • $\begingroup$ Oh sorry forgot the second error in your code. You use ^ for the exponent but you actually need to use ** for exponents in python. $\endgroup$ – A Kareem May 5 '20 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.