简体   繁体   English

带有numpy的python中的标量和ndarray错误

[英]Error with scalar and ndarray in python with numpy

I have small problem but I can't just find an easy answer.I feel stupid for asking it. 我有一个小问题,但我找不到一个简单的答案,问这个问题我很傻。

How can i multiply a scalar with a numpy.ndarray? 如何将标量与numpy.ndarray相乘?

import fileinput,sys,re,csv,scipy,os,numpy,pylab
from collections import defaultdict
from matplotlib.pyplot import *
from StringIO import StringIO
import numpy as num
a = open("testt.txt", "r")
b=[ raw.strip().split() for raw in a]
c=np.array(b)
d=c.transpose()  
data=np.loadtxt("uu.txt",skiprows=1,dtype=None,delimiter='\t')
t1 = data[:,0]
t=(1/1000)*t1
s = data[:,9]
pylab.plot(t1, s)
pylab.xlabel('time (ms)')
pylab.ylabel('Zone height (mm)')
pylab.grid(True)
pylab.savefig('simple_plot')
pylab.show()

The error is in the line t=(1/1000)*t1 which gives me the error: TypeError: unsupported operand type(s) for *: 'int' and 'numpy.ndarray'. 错误在t =(1/1000)* t1行中,这给了我错误:TypeError:*:'int'和'numpy.ndarray'不受支持的操作数类型。 The text file uu.txt is an 60*60 matrix with an header as the first line.I can post it if its necessary. 文本文件uu.txt是一个60 * 60的矩阵,标题为第一行。如有必要,我可以将其发布。

Thanks 谢谢

It's a tad surprising. 这有点令人惊讶。 If data is a ndarray , then t1=data[:,0] is a ndarray too and you shouldn't have any problem multiplying it by an int. 如果data是一个ndarray ,则t1=data[:,0]也是一个ndarray ,将它乘以一个int不会有任何问题。

Still: 仍然:

  • You could check the type of t1 as well as its .shape . 您可以检查t1的类型及其.shape
  • You can force t1 to be a ndarray just in case: t1=np.asarray(data[:,0]) 您可以强制t1作为ndarray ,以防万一: t1=np.asarray(data[:,0])
  • I'm pretty sure you don't want to calculate (1/1000) but (1./1000) instead: (1/1000) is 0 by virtue of integer division... 我很确定您不想计算(1/1000)而是(1/1000) (1./1000) :由于整数除法, (1/1000)0 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM