pandas 如何将熊猫数据框的两列相乘(行乘法)并将结果存储在新列中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45155063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:01:43  来源:igfitidea点击:

How to multiply two columns of a pandas data-frame (row multiplication) and store the result in a new column?

pythonpython-3.xpandas

提问by Czar.Wolfgang

Command

命令

df_main['Ranking'] = df_main['Porosity']*['Permeability']gives -

df_main['Ranking'] = df_main['Porosity']*['Permeability']给 -

TypeError: can't multiply sequence by non-int of type 'str'

类型错误:不能将序列乘以“str”类型的非整数

The attacehd picture (https://i.stack.imgur.com/0Asu3.png) has more information. My code snippet is at i.stack.imgur.com/ehqF5.png)

attacehd 图片(https://i.stack.imgur.com/0Asu3.png)有更多信息。我的代码片段位于 i.stack.imgur.com/ehqF5.png)

More info: https://i.stack.imgur.com/0Asu3.png

更多信息:https: //i.stack.imgur.com/0Asu3.png

回答by Miriam Farber

First you need to convert the column type of the two columns to floats (otherwise you cannot multiply them). You can do that as follows:

首先需要将两列的列类型转换为浮点数(否则不能相乘)。你可以这样做:

df_main[['Porosity', 'Permeability']] = df_main[['Porosity', 'Permeability']].astype(float)

Then you can define the new column via multiplication:

然后您可以通过乘法定义新列:

df_main['Ranking'] = df_main['Porosity']*df_main['Permeability']