简体   繁体   English

如何在python中使用数据框进行行级计算?

[英]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.

相关问题 如何在Python中的数据框中进行累加计算? - How to do accumulative calculation in data frame in Python? 如何在python中遍历数据框中的一列,得到该行对应的算术计算 - How to iterate through a column in data frame in python and get the arithmetic calculation corresponding to the row 如何在python中使用时间戳在数据框中进行小时计算? - How to do hour wise calculation in a data frame using time stamp in python? 如何将数据框中一行的值与另一个数据框中的多行进行比较(包括计算) - How to compare the values of a row in a data frame with multiple rows from another data frame (include calculation) 重塑数据框并为每一行应用计算 - reshaping data frame and applying calculation for each row 如何识别python数据框中条件的第一次出现并对其进行计算? - How to identify a first occurence of a condition in python data frame and perform a calculation on it? 如何针对其他数据帧的行查询 python 数据帧? - How to query python data frame against row of other data frame? 如何使用 python 重新排列数据框行? - How to rearrange row of data frame using python? 如何将单元格中的合并数据提取到 python 数据框中的行中? - How do I extract merged data from a cell into its row in a python data frame? 如何在一列,一行一行地比较Pandas数据帧? - How to do Pandas data frame comparison on one column, row by row?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM