我有一个pandas DataFrame (忽略DataFrame的索引)
Tab Ind Com Val
4 BAS 1 1 10
5 BAS 1 2 5
6 BAS 2 1 20
8 AIR 1 1 5
9 AIR 1 2 2
11 WTR 1 1 2
12 WTR 2 1 1
还有熊猫系列
Ind
1 1.208333
2 0.857143
dtype: float64
我想将DataFrame的Val列的每个元素与具有相同IND值的序列的元素相乘。我该如何解决这个问题呢?pandas.DataFrame.mul只匹配索引,但我不想转换DataFrame。
发布于 2018-12-19 05:54:29
看起来pandas.DataFrame.join
可以解决你的问题:
temp = df.join(the_series,on='Ind', lsuffix='_orig')
df['ans'] = temp.Val*temp.Ind
输出
Tab Ind Com Val ans
4 BAS 1 1 10 12.083330
5 BAS 1 2 5 6.041665
6 BAS 2 1 20 17.142860
8 AIR 1 1 5 6.041665
9 AIR 1 2 2 2.416666
11 WTR 1 1 2 2.416666
12 WTR 2 1 1 0.857143
或者使用更紧凑的语法(thanks W-B)实现相同目标的另一种方法
df1['New']=df1.Ind.map(the_series).values*df1.Val
https://stackoverflow.com/questions/53841573
复制相似问题