首页 > 解决方案 > 减法和乘法列

问题描述

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

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

标签: pythonpandaspython-2.7numpy

解决方案


如果您只想减去第一行,然后乘以第 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 数组。如果你不这样做,那么 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

推荐阅读