【问题标题】:subtraction and multiplication column wise减法和乘法列
【发布时间】:2019-10-31 18:06:47
【问题描述】:

我需要做减法和乘法列。按照以下格式。

df1

 A  B   C   D   E
10  11  13  12  15
11  13  10  15  13

可以有“n”个列。

formula - subtraction: 
column 1 - column B, them col B - col C then col C - col D and so on. 

formula - Multiplication: 
row1 multiply by row2 

预期输出:

                   A      B   C    D    E
SUBTRACTION       -1     -2   1   -3    15
MULTIPLCATION    -11     -26  10 -45    195

【问题讨论】:

  • 你只想减去第一行吗?
  • 是的,对于 A = 10 - 11 = -1,B = 11-13 = -2,对于 C = 13-12 = 1,对于 D = 12 -15 = -3,对于E = 15,因为它是。等等……

标签: python pandas python-2.7 numpy


【解决方案1】:

如果只想减去第一行再乘以第二行:

arr = df.values
df
    A   B   C   D   E
0   10  11  13  12  15
1   11  13  10  15  13

df.iloc[0, :-1] = arr[0, :-1] - arr[0, 1:]
df

     A  B   C   D   E
0   -1  -2  1   -3  15
1   11  13  10  15  13

.values 会将 Data Frame 转换为 numpy 数组。如果你不这样做,那么 pandas 只会减去相应的列。

df.iloc[1,:] = arr[0] * arr[1]
df
     A  B   C    D   E
0   -1  -2  1   -3   15
1   -11 -26 10  -45  195

然后改变索引:

df.index = ['SUBTRACTION', 'MULTIPLCATION']
df

                 A   B   C  D   E
SUBTRACTION      -1 -2   1  -3  15
MULTIPLCATION   -11 -26  10 -45 195

【讨论】:

    【解决方案2】:

    使用indexing,然后使用mulsub

    df.iloc[0,:-1] = df.iloc[0,:-1].sub(df.iloc[0,1:].to_numpy())
    df.iloc[1,:] = df.iloc[0,:].mul(df.iloc[1,:])
    df.index = ['SUBTRACTION', 'MULTIPLCATION']
    
    print(df)
                    A   B   C   D    E
    SUBTRACTION    -1  -2   1  -3   15
    MULTIPLCATION -11 -26  10 -45  195
    

    【讨论】:

      【解决方案3】:

      或者为什么不:

      >>> df.iloc[0] = df.iloc[0].sub(df.iloc[0].shift(-1)).fillna(df.iloc[0])
      >>> df.iloc[1] = df.iloc[0].mul(df.iloc[1])
      >>> df
            A     B     C     D      E
      0  -1.0  -2.0   1.0  -3.0   15.0
      1 -11.0 -26.0  10.0 -45.0  195.0
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2020-02-13
        • 1970-01-01
        • 2023-03-30
        • 2017-10-16
        • 2021-07-18
        • 2014-05-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多