I am trying to find a way to bring the new calculated columns back to the dataframe after doing the multiplication. However, I want them to replace the value under original columns like '2018, 2019, 2020'. Is there a way to do it alongside with the multiplication, especially if I have a long list of columns to be multiplied?
import pandas as pd
df1 = pd.DataFrame({
'ID': ['a1', 'b1', 'c1'],
'2018': [1, 5, 9],
'2019': [2, 6, 10],
'2020': [3, 7, 11]})
df2 = pd.DataFrame({
'ID': ['a1', 'b1'],
'percentage': [0.6, 0.4]})
df1.filter(regex='2018|2019|2020').multiply(df2["percentage"], axis="index")
Expected:
ID 2018 2019 2020
0 a1 0.6 1.2 1.8
1 b1 2.0 2.4 2.8
2 c1 NaN NaN NaN