python - 减法和乘法列
问题描述
我需要做减法和乘法列。按照以下格式。
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
解决方案
如果您只想减去第一行,然后乘以第 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
推荐阅读
- javascript - 如何使用输入类型=颜色更改背景颜色?
- c++ - 如何在基类中调用虚函数?(C++)
- docker - 无需root的podman容器之间的通信
- php - PHP - 如果 int 达到 n
- sql - 如何在 SQL 中将表声明为变量
- android - Android Jetpack Security MasterKey(s) 稳定版
- scala - Scala、websockets 和不可变数据
- html - 为什么我的 RoR 应用程序中的 CSS 会根据我是在生产还是开发中运行而发生变化?
- zoom-sdk - 通过使用 @zoomus/websdk 的应用程序加入缩放网络研讨会时下载文件
- mysql - MySql 能否与 Node Js 框架一起正常工作?