简体   繁体   English

将 pandas DataFrame 列与 Series 相乘

[英]Multiply pandas DataFrame column with a Series

I want to multiply a pandas DataFrame df with Series s :我想将 pandas DataFrame df与 Series s相乘:

df = pd.DataFrame([[0,0,10],[0,1,11],[1,0,12],[1,1,13],[2,0,14],[2,1,15]], columns=['a','b','val'])
s = pd.Series([2,3])
df:                s:
    a b val          
___________        ______
0   0 0 10         0   2
1   0 1 11         1   3
2   1 0 12
3   1 1 13
4   2 0 14
5   2 1 15

such that the indices of the Series [0, 1] are matched with column b of the DataFrame [0, 1, 0, 1, 0, 1], ie I expect the column val to change from这样系列 [0, 1] 的索引与 DataFrame [0, 1, 0, 1, 0, 1] 的b列匹配,即我希望列val

[10, 11, 12, 13, 14, 15]

to

[20, 33, 24, 39, 28, 45]

It seems like a trivial problem, and I tried MultiIndex and GroupBy , .mul() .apply() .... I just can't seem to figure it out.这似乎是一个微不足道的问题,我尝试MultiIndexGroupBy.mul() .apply() .... 我似乎无法弄清楚。 Really appreciate your help!非常感谢您的帮助!

Map s on b then multiply by val :b上映射s然后乘以val

df['val2'] = df['b'].map(s) * df['val']

Output:输出:

>>> df
   a  b  val  val2
0  0  0   10    20
1  0  1   11    33
2  1  0   12    24
3  1  1   13    39
4  2  0   14    28
5  2  1   15    45

>>> df['b'].map(s)
0    2
1    3
2    2
3    3
4    2
5    3
Name: b, dtype: int64

You can also do index matching by using the level argument of df.mul :您还可以使用df.mullevel参数进行索引匹配:

>>> df['new_val'] = df.set_index('b', append=True)['val']
                      .mul(s, level=1)
                      .reset_index(drop=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM