Python:对numpy数组的高效操作

R.B*_*ahl 0 python numpy

说我有一个numpy数组x:

x = array([[  3,   2,   1],
           [  3,  25,  34],
           [ 33, 333,   3],
           [ 43,  32,   2]])
Run Code Online (Sandbox Code Playgroud)

我想在没有显式写入for循环的情况下执行以下操作,即说一个在内置循环中使用自动的方法;

1)将所有1列的第2列替换为ie

x = array([[  3,   1,   1],
           [  3,   1,  34],
           [ 33,   1,   3],
           [ 43,   1,   2]])
Run Code Online (Sandbox Code Playgroud)

2)在原始数组中,将第3列替换为第2列和第3列的乘积

x = array([[  3,   2,   1*2],
           [  3,  25,  34*25],
           [ 33, 333,   3*333],
           [ 43,  32,   2*32]])
Run Code Online (Sandbox Code Playgroud)

3)最后,我想基于一个条件替换原始数组中的第二列

x[1] = 0  if x[0] > 5 else 4 
Run Code Online (Sandbox Code Playgroud)

即阵列现在看起来像:

x = array([[  3,   4,   1],
           [  3,   4,  34],
           [ 33,   0,   3],
           [ 43,   0,   2]])
Run Code Online (Sandbox Code Playgroud)

有什么建议 ?谢谢 !

Jon*_*nts 6

关于numpy的文档值得一读,因为这是相当基本的东西......

  1. x[:,1] = 1
  2. x[:,2] *= x[:,1]
  3. x[:,1] = np.where( x[:,0] > 5, 0, 4 )

  • 使用`x [:,2]*= x [:,1]`可以改善数字2 - 这可以节省临时数组的创建. (2认同)