如何将 pandas 数据框中的每一行乘以不同的值 [英] How to multiply each row in pandas dataframe by a different value

查看:69
本文介绍了如何将 pandas 数据框中的每一行乘以不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将熊猫数据帧的每一行乘以一个不同的值,并想知道这样做的最佳方法是什么.

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.

推荐答案

方法为 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆