[英]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.这似乎是一个微不足道的问题,我尝试MultiIndex
和GroupBy
, .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.mul
的level
参数进行索引匹配:
>>> 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.