问题
Lets say I have a pandas series:
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:
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.
How do I do this?
回答1:
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
回答2:
You can multiply the dataframes directly.
x * y
回答3:
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:
new_x = df.mul(s.values, axis=0)
回答4:
As Abdou points out, the answer is
z = x.apply(lambda col: col*y)
Moreover, if you instead have a DataFrame, e.g.
y = pandas.DataFrame({"colname": [1,-1,-1]})
Then you can do
z = x.apply(lambda z: z*y["colname"])
来源:https://stackoverflow.com/questions/39948935/multiplying-pandas-dataframe-and-series-element-wise