简体   繁体   English

Python .npy文件:如何乘或除数据?

[英]Python .npy file: how to multiply or divide the data?

I have data file in .npy format. 我有.npy格式的数据文件。 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. 输入ab是列表,因此您无法执行这些操作。 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 - 您需要通过调用np.array()将这些输入之一转换为NumPy数组,然后执行这些操作,如下所示-

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. 如果需要将输出保存为列表,则需要通过调用ndarray.tolist()将由此获得的NumPy数组转换回列表,其中ndarray是NumPy数组的输出。 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. 就像说的那样, ab是列表。 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: 在我的示例中使用lists-comprehencion:

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]

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

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