Python 按列进行减法和乘法

Python 按列进行减法和乘法,python,pandas,python-2.7,numpy,Python,Pandas,Python 2.7,Numpy,我需要做减法和乘法。按照以下格式 df1 列数可以为“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 df.iloc[1,:] = arr[0] * arr[1] df A B C D E 0 -1 -2 1

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

df1

列数可以为“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 
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
预期产出:

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

使用
索引
,然后使用
mul
sub
作为:

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

如果只想先减去第一行,然后再乘以第2行:

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
将数据帧转换为numpy数组。如果不这样做,熊猫将只减去相应的列

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 
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
或者为什么不:

>>> 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
>>> 

你只想减去第一行吗?是的,比如A=10-11=-1,B=11-13=-2,C=13-12=1,D=12-15=-3,E=15。等等