[英]How to do calculation on row level with data frame in python?
I have a data frame in python, and I want to do a simple calculation on row level.我在python中有一个数据框,我想在行级别做一个简单的计算。 How can can I do it in Python?我怎样才能在 Python 中做到这一点?
Current Table当前表
product ct产品CT | cost1成本1 | cost2成本2 | cost3成本3 |
---|---|---|---|
1000 1000 | 10 10 | 100 100 | 20 20 |
2000 2000年 | 200 200 | 100 100 | 30 30 |
Calculation Concept计算概念
product ct产品CT | cost1成本1 | cost2成本2 | cost3成本3 |
---|---|---|---|
1000 1000 | 10/1000 10/1000 | 100/1000 100/1000 | 20/1000 20/1000 |
2000 2000年 | 200/2000 200/2000 | 100/2000 100/2000 | 30/2000 30/2000 |
Wanted Output想要的输出
product ct产品CT | cost1成本1 | cost2成本2 | cost3成本3 |
---|---|---|---|
1000 1000 | 0.01 0.01 | 0.1 0.1 | 0.02 0.02 |
2000 2000年 | 0.1 0.1 | 0.05 0.05 | 0.015 0.015 |
You can use pandas.DataFrame.filter
to get the required columns (If you have the static columns, you can manually assign them to a list), and then use div
to divide, and finally assign back all the values to the selected columns:您可以使用pandas.DataFrame.filter
来获取需要的列(如果您有静态列,您可以手动将它们分配给一个列表),然后使用div
进行划分,最后将所有值分配回所选列:
>>> cols = df[:0].filter(like='cost').columns.to_list()
>>> df[cols] = df[cols].div(df['product ct'], axis=0)
OUTPUT:输出:
product ct cost1 cost2 cost3
0 1000 0.01 0.10 0.020
1 2000 0.10 0.05 0.015
Try using divide
along the required axis:尝试沿所需轴使用divide
:
df[["cost1", "cost2", "cost3"]] = df[["cost1", "cost2", "cost3"]].divide(df["product ct"], axis=0)
>>> df
product ct cost1 cost2 cost3
0 1000 0.01 0.10 0.020
1 2000 0.10 0.05 0.015
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.