使用numpy对python中二维数组的数值运算

时间:2017-09-29 06:24:02

标签: python numpy

我有以下数组。如何将数值运算应用于每个x,y作为
x * 3 + 1,(y + 2)* 2使用numpy。

A = [[2,4],[1,5],[6,3],[],[],[],[] ..... [x,y]]

提前致谢

4 个答案:

答案 0 :(得分:0)

明显的清单方法:

In [111]: A = [[2,4],[1,5],[6,3]]
In [112]: def foo(x,y):
     ...:     return x*3+1,(y+2)*2 
     ...: 
In [113]: [foo(x,y) for x,y in A]
Out[113]: [(7, 12), (4, 14), (19, 10)]

创建一个数组,并将列传递给函数:

In [114]: AA = np.array(A)
In [115]: AA
Out[115]: 
array([[2, 4],
       [1, 5],
       [6, 3]])
In [116]: foo(AA[:,0], AA[:,1])
Out[116]: (array([ 7,  4, 19]), array([12, 14, 10]))

结果是一个数组元组;转置可以将其转换为数组:

In [117]: np.transpose(_)
Out[117]: 
array([[ 7, 12],
       [ 4, 14],
       [19, 10]])

答案 1 :(得分:0)

你可以使用一个简单的嵌套for循环,但首先要确保它是一个numpy数组

import numpy as np

a = np.array([[1,2],[4,5],[7,8],[10,11]])

rows = a.shape[0]
cols = a.shape[1]

for x in range(0, rows):
    for y in range(0, cols, 2): # the last param 2 is the incremented by number
        #do you operation here
        print (a[x,y])
        print (a[x,y+1])
        print (a[x,y]*3+1,(a[x,y+1]+2)*2)

答案 2 :(得分:0)

import numpy as np
#Convert normal array to np array
A = np.array([[2,4],[1,5],[6,3]])
print A
B = np.array([A[:,0]*3 + np.ones(A.shape[0]), (A[:,1] + np.ones(A.shape[0])*2)*2], float).T
print B #This is the array with operations done on it.

答案 3 :(得分:0)

直向前:

import numpy as np

a = np.array([[2,4],[1,5],[6,3]])
a[:,0] = a[:,0]*3+1
a[:,1] = (a[:,-1]+2)*2

print(a)

输出:

[[ 7 12]
 [ 4 14]
 [19 10]]