I have data file in .npy format. But for simplicity, let's take the following case
data={}
data["a"]=[1.,2.,3.,4.,5.]
data["b"]=[10,20,30,40,50]
a=data["a"]
b=data["b"]
c1=a*b
c2=a/b
c3=np.sqrt(a/b)
This gives following error
TypeError: can't multiply sequence by non-int of type 'list'
TypeError: unsupported operand type(s) for /: 'list' and 'list'
How do we do above operations with these type of arrays? Thank you
Those inputs a
and b
are lists and as such you can't perform those operations. You need to convert either one of those inputs to a NumPy array with a call to np.array()
and then perform those operations, like so -
In [21]: a
Out[21]: [1.0, 2.0, 3.0, 4.0, 5.0]
In [22]: b
Out[22]: [10, 20, 30, 40, 50]
In [23]: np.array(a)*b # Option 1
Out[23]: array([ 10., 40., 90., 160., 250.])
In [24]: a*np.array(b) # Option 2
Out[24]: array([ 10., 40., 90., 160., 250.])
In [25]: np.array(a)/b # Option 1
Out[25]: array([ 0.1, 0.1, 0.1, 0.1, 0.1])
In [26]: a/np.array(b) # Option 2
Out[26]: array([ 0.1, 0.1, 0.1, 0.1, 0.1])
In [27]: np.sqrt(np.array(a)/b) # Option 1
Out[27]: array([ 0.31622777, 0.31622777, 0.31622777, 0.31622777, 0.31622777])
In [28]: np.sqrt(a/np.array(b)) # Option 2
Out[28]: array([ 0.31622777, 0.31622777, 0.31622777, 0.31622777, 0.31622777])
If you need to save the output as a list, you need to convert the NumPy array thus obtained back to a list with a call to ndarray.tolist()
, where ndarray is the NumPy array output. Thus, for the multiplication case you would have -
In [29]: (np.array(a)*b).tolist()
Out[29]: [10.0, 40.0, 90.0, 160.0, 250.0]
as it says, a
and b
are lists. I think you are trying to do operations on the list items so you will have to iterate through each item. you can do list comprehension like this:
c1 = [x*y for x,y in zip(a,b)]
c2 = [x/y for x,y in zip(a,b)]
and etc
Use lists-comprehencion like in my example:
data={}
data["a"]=[1.,2.,3.,4.,5.]
data["b"]=[10,20,30,40,50]
a=data["a"]
b=data["b"]
c1 = [(i*j) for i,j in zip(a,b)]
c2 = [(i/j) for i,j in zip(a,b)]
c3 = [np.sqrt(i/j]) for i,j in zip(a,b)]
outputs:
#c1
[10.0, 40.0, 90.0, 160.0, 250.0]
#c2
[0.1, 0.1, 0.1, 0.1, 0.1]
#c3
[0.31622776601683794, 0.31622776601683794, 0.31622776601683794, 0.31622776601683794, 0.31622776601683794]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.