如何使用numpy进行逐列减法?

时间:2019-02-10 06:38:06

标签: python numpy

假设我有:

array([[ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3],
       [ 5,  4,  3,  3]])

然后我有

array([1, 2, 3, 4])

我想用1d数组中的相应列值减去原始矩阵中的每一列。

所以,我希望它成为

array([[ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1],
       [ 4,  2,  0,  -1]])

如何在numpy中实现?

1 个答案:

答案 0 :(得分:2)

这比您想象的要容易得多

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/mobile_navigation"
        app:startDestination="@id/mainFragment">

<fragment android:id="@+id/mainFragment"
          android:name="com.haidar.mediasaver.fragments.MainFragment"
          android:label="main_fragment"
          tools:layout="@layout/main_fragment">
    <argument android:name="name"
              app:argType="string"/>
</fragment>

NumPy自动广播,因此只需使用In [1]: import numpy as np In [2]: arr = np.array([[ 5, 4, 3, 3], ...: [ 5, 4, 3, 3], ...: [ 5, 4, 3, 3], ...: [ 5, 4, 3, 3], ...: [ 5, 4, 3, 3]]) In [3]: sub = np.array([1, 2, 3, 4]) In [4]: arr - sub Out[4]: array([[ 4, 2, 0, -1], [ 4, 2, 0, -1], [ 4, 2, 0, -1], [ 4, 2, 0, -1], [ 4, 2, 0, -1]]) 运算符!