TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

StackOverflow https://stackoverflow.com/questions/21687581

  •  09-10-2022
  •  | 
  •  

Question

f=np.loadtxt('Single Small Angle 1.txt',unpack=True,skiprows=2)
g=np.loadtxt('Single Small Angle 5.txt',unpack=True,skiprows=2)

x = f-g[:,:11944]
t=range(len(x))
m=math.log10(abs(x))

np.polyfit(t,m)

plt.plot(t,abs(x))
plt.show()

I'm just not sure on how to fix my issue. It keeps saying:

m=math.log10(abs(x))
TypeError: only length-1 arrays can be converted to Python scalars

No correct solution

OTHER TIPS

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

Here is another way to reproduce this error in Python2.7 with numpy:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)   #note the lack of tuple format for a and b
print(c) 

The np.concatenate method produces an error:

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

If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b))  #surround a and b with parens, packaging them as a tuple
print(c) 

Then it prints:

[1 2 3 4 5 6]

What's going on here?

That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".

In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top