在 Pandas 中用标量乘以列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16112209/
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-13 20:46:39  来源:igfitidea点击:

Multiplying Columns by Scalars in Pandas

pythonpandas

提问by Eduardo Sahione

Suppose I have a pandas DataFrame with two columns named 'A' and 'B'.

假设我有一个 Pandas DataFrame,其中有两列名为“A”和“B”。

Now suppose I also have a dictionary with keys 'A' and 'B', and the dictionary points to a scalar. That is, dict['A'] = 1.2 and similarly for 'B'.

现在假设我还有一个带有键“A”和“B”的字典,并且字典指向一个标量。也就是说, dict['A'] = 1.2 和 'B' 类似。

Is there a simple way to multiply each column of the DataFrame by these scalars?

有没有一种简单的方法可以将 DataFrame 的每一列乘以这些标量?

Cheers!

干杯!

回答by Wes McKinney

As Wouter said, the recommended method is to convert the dict to a pandas.Series and multiple the two objects together:

正如 Wouter 所说,推荐的方法是将 dict 转换为 pandas.Series 并将两个对象组合在一起:

result = df * pd.Series(myDict)

result = df * pd.Series(myDict)

回答by BrenBarn

You could do:

你可以这样做:

for col in df.columns:
     df[col] *= myDict[col]