问题描述
我试图将熊猫数据帧的每一行乘以一个不同的值,并想知道这样做的最佳方法是什么.
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.
例如,如果我具有以下数据框:
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]
在此示例中,我希望第一行中的每个项目都乘以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
因此,结果应为:
0 1 2
0 -1.283316 0.849488 1.936060
1 -207.8575 -87.1570 -97.0261
我尝试过:
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.
推荐答案
方法为 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
这篇关于如何将 pandas 数据框中的每一行乘以不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!