pandas 将熊猫数据框和系列相乘,元素明智

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

Multiplying pandas dataframe and series, element wise

pythonpandas

提问by wwl

Lets say I have a pandas series:

假设我有一个Pandas系列:

import pandas as pd
x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
y = pd.Series([-1, 1, -1])

I want to multiply x and y in such a way that I get z:

我想用 x 和 y 相乘得到 z:

z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] })

In other words, if element j of the series is -1, then all elements of the j-th row of x get multiplied by -1. If element k of the series is 1, then all elements of the j-th row of x get multiplied by 1.

换句话说,如果系列的元素 j 是 -1,那么 x 的第 j 行的所有元素都乘以 -1。如果系列的元素 k 为 1,则 x 的第 j 行的所有元素都乘以 1。

How do I do this?

我该怎么做呢?

回答by coder

You can do that:

你可以这样做:

>>> new_x = x.mul(y, axis=0)
>>> new_x
   0  1  2
0 -1 -4 -7
1  2  5  8
2 -3 -6 -9

回答by Samuel Dare

You can multiply the dataframes directly.

您可以直接将数据帧相乘。

x * y

回答by Lawrence

Although this question is old, I'll add that if the function returns a bunch of nonsensical NaNs, you should multiply by the values of the series in question like so:

虽然这个问题很老,但我会补充说,如果函数返回一堆无意义的 NaN,你应该乘以有问题的系列的值,如下所示:

new_x = df.mul(s.values, axis=0)

回答by wwl

As Abdou points out, the answer is

正如阿卜杜指出的那样,答案是

z = x.apply(lambda col: col*y)

Moreover, if you instead have a DataFrame, e.g.

此外,如果你有一个 DataFrame,例如

 y = pandas.DataFrame({"colname": [1,-1,-1]})

Then you can do

然后你可以做

 z = x.apply(lambda z: z*y["colname"])