pandas 如何将熊猫数据框中的每一行乘以不同的值

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

How to multiply each row in pandas dataframe by a different value

pythonpandas

提问by johnchase

I am trying to multiply each row of a pandas dataframe by a different value and wondering what the best way to do this is.

我正在尝试将 Pandas 数据帧的每一行乘以不同的值,并想知道这样做的最佳方法是什么。

For example if I have the following dataframe:

例如,如果我有以下数据框:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(2, 3))
df
     0          1           2
0   -1.283316   0.849488    1.936060
1   -2.078575   -0.871570   -0.970261

I want to multiply each element of each row by a different in a list or array

我想将每行的每个元素乘以列表或数组中的不同元素

vals = [1, 100]

In this example I want each item in the first row to be multiplied by 1 and each item in the second row to be multiplied by 100

在这个例子中,我希望第一行中的每个项目都乘以 1,第二行中的每个项目都乘以 100

the result should therefore be:

因此,结果应该是:

     0          1           2
0   -1.283316   0.849488    1.936060
1   -207.8575   -87.1570    -97.0261

I have tried:

我试过了:

df * vals
df.multiply(vals)
df.multiply(vals, axis=1)

None of which work, although I was not expecting them too, based on my understanding of what that code should do. I can't figure out a concise way to do this with pandas, any help is appreciated, thanks.

根据我对代码应该做什么的理解,这些都不起作用,尽管我也没有预料到它们。我想不出用Pandas来做这件事的简洁方法,感谢任何帮助,谢谢。

回答by ayhan

The method is mul:

方法是mul

df.mul([1, 100], axis=0)
Out[17]: 
            0          1         2
0   -1.198766  -1.340028  1.990843
1  113.890468 -68.177755 -9.060228