Dhimmel90
Dhimmel90

Reputation: 39

Multiply two dataframes with same column names but different index

I have two dataframes, one with data, one with a list of forecasting assumptions. The column names correspond, but the index levels do not (by design). Please show me how to multiply columns A, B, and C in df1 by the relevant columns in df2, as in my example below, and with the remainder of the original dataframe (aka column D) intact. Thanks!

df1list=[1,2,3,4,5,6,7,8,9,10]
df2list=[2017]
df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'), index=list(df1list))
df2 = pd.DataFrame(np.random.randint(1,4,size=(1, 3)), columns=list('ABC'), index=list(df2list))

Upvotes: 0

Views: 856

Answers (1)

Tom
Tom

Reputation: 8800

>>> df[['A','B','C']] * df2.values

      A    B    C
1    81  168  116
2    21    8    6
3   147  108   52
4    54   64  114
5    48   16   20
6    72  116   12
7    36  188  178
8    90   96  162
9    63  166  156
10  120   22   10

So to overwrite you can do:

df.loc[:,['A','B','C']] = df[['A','B','C']] * df2.values

And I guess to be more programmatic you can do:

df[df2.columns] *= df2.values

Upvotes: 2

Related Questions