1

I have two data frames that look like this:

            A   B
date        
2017-10-5   2   3
2017-10-6   5   5
2017-11-5   7   8
2017-11-6   11  13


             W1     W2
date        
2017-09-30  -0.2    0.01
2017-10-31  -0.003  0.04

I would like to create a new data frame that contains the following:

            W1 * A       W2 * B
date        
2017-10-5   -0.2 * 2     0.01 * 3
2017-10-6   -0.2 * 5     0.01 * 5
2017-11-5   -0.003 * 7   0.04 * 8
2017-11-6   -0.003 * 11  0.04 * 13
1
  • The date is the index? Why are you multiplying non-matching indices? Commented Oct 31, 2018 at 22:03

2 Answers 2

1

Use np.repeat on df2 and multiply. It looks like the index plays no part here.

df1 = df1.mul(np.repeat(df2.values, 2, axis=0))

Or, more generally,

df1 = df1.mul(np.repeat(df2.values, len(df1) // len(df2), axis=0))
print(df1)
               A     B
date                  
2017-10-5 -0.400  0.03
2017-10-6 -1.000  0.05
2017-11-5 -0.021  0.32
2017-11-6 -0.033  0.52

Where len(df1) // len(df2) computes the ratio of their sizes.

Sign up to request clarification or add additional context in comments.

1 Comment

The index does indeed play no role here. Thanks for your prompt answer!
0

In case the index does mean something, i.e. you have a value that changes on a certain date and you want to keep using it until it changes the next time. You can then use the reindex command with the argument method='ffill' to create a dataframe that is aligned to the original dataframe. Here's how it looks like:

import pandas as pd
import dateutil

df = pd.DataFrame([['2017-10-5',2,3],
                  ['2017-10-6',5,5],
                  ['2017-11-5',7,8],
                  ['2017-11-6',11,13]],
                  columns = ['date','A','B'])
df['date'] = df['date'].apply(dateutil.parser.parse)
df = df.set_index('date')

wdf = pd.DataFrame([['2017-09-30',-0.2,0.01],
                    ['2017-10-31',-0.03,0.04]],
                     columns=['date','W1','W2'])
wdf['date'] = wdf['date'].apply(dateutil.parser.parse)
wdf = wdf.set_index('date')
wdf_r = wdf.reindex(df.index,
                    method='ffill')

res = df.drop(['A','B'],axis=1).assign(W1_x_A = wdf_r.W1 * df.A,
                                       W2_x_B = wdf_r.W2 * df.B)
print(res)

which outputs

            W1_x_A  W2_x_B
date                      
2017-10-05   -0.40    0.03
2017-10-06   -1.00    0.05
2017-11-05   -0.21    0.32
2017-11-06   -0.33    0.52

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.