[Tutor] TypeError: only length-1 arrays can be converted to Python scalars
Peter Otten
__peter__ at web.de
Thu Jan 26 13:01:47 CET 2012
stm atoc wrote:
> Hi,
>
> I have a question regarding the TypeError.
>
> I have this script as follows in Python. I have run a program in Fortran:
>
> # coding: utf-8
> from pylab import *
> import numpy
> import matplotlib.pyplot as pyplot
> import matplotlib.mlab as mlab
>
> t=3600
> N = 100
> dz = 1.0
>
> with open("act_out.list", "r") as f:
> z = numpy.array([float(v) for v in f.readline().split()[1:]])
> zm = z*1.0e6
>
> a = numpy.loadtxt("act_out.list", skiprows=3)
> t=a[:,0]
> nu = a[0:,1:N+1]
> Conc = a[:, N+1:]
> hsml=zeros((103))
> cprof=zeros((103))
>
> hsml[0]=-1300.
> hsml[-2]=-300.
> hsml[-1]=0.
> hsml[1:-2]=z*1000000-300.
>
> cprof[0]=50.
> cprof[-2]=500.
> cprof[-1]=500.
>
> idx=int(where(t==1800)[0])
> cprof[1:-2]=Conc[idx]
>
> lw = 2.0
> dpi = 80
> figure(figsize=(8,8),dpi=dpi)
> pyplot.plot(cprof,hsml,'r-')
>
> pyplot.xlabel('$Conc, mmol C m^3$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
>
> legend()
> savefig('Conc.png')
> show()
>
> after runing Python, I hav ethis massage:
>
> TypeError: only length-1 arrays can be converted to Python scalars
>
> Any suggestion? in fact, what I missed and what I should add to have
> a right result!
By retyping the error message or omitting the traceback you are stripping
off information that is valuable for debugging your problem. Always cut and
paste the complete traceback.
Also, I cannot run your script as it relies upon data that you don't
provide. Again, debugging becomes easier if you make your script self-
contained, e. g. set 'a' to some value explicitly with
a = numpy.array([...])
Anyway, here's my guess:
The t array has more than one 1800 entry:
>>> t = numpy.array([1., 1800., 1800.])
>>> numpy.where(t==1)
(array([0]),)
>>> int(numpy.where(t==1)[0])
0
>>> int(numpy.where(t==1800)[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only length-1 arrays can be converted to Python scalars
I don't know what you are trying to do; if you are content with the index of
the first occurrence of 1800 and are sure there is always at least one you
could write
idx = numpy.where(t==1800)[0][0]
More information about the Tutor
mailing list