2

I couldn't find an efficient away of doing that. I have below DataFrame in Python with columns from A to Z

     A    B    C ...   Z
0  2.0  8.0  1.0 ... 5.0
1  3.0  9.0  0.0 ... 4.0
2  4.0  9.0  0.0 ... 3.0
3  5.0  8.0  1.0 ... 2.0
4  6.0  8.0  0.0 ... 1.0
5  7.0  9.0  1.0 ... 0.0

I need to multiply each of the columns from B to Z by A, (B x A, C x A, ..., Z x A), and save the results on new columns (R1, R2 ..., R25). I would have something like this:

     A    B    C ...   Z    R1   R2  ...  R25
0  2.0  8.0  1.0 ... 5.0  16.0  2.0  ... 10.0
1  3.0  9.0  0.0 ... 4.0  27.0  0.0  ... 12.0
2  4.0  9.0  0.0 ... 3.0  36.0  0.0  ... 12.0
3  5.0  8.0  1.0 ... 2.0  40.0  5.0  ... 10.0
4  6.0  8.0  0.0 ... 1.0  48.0  0.0  ... 6.0
5  7.0  9.0  1.0 ... 0.0  63.0  7.0  ... 0.0

I was able to calculate the results using below code, but from here I would need to merge with original df. Doesn't sound efficient. There must be a simple/clean way of doing that.

df.loc[:,'B':'D'].multiply(df['A'], axis="index")

That's an example, my real DataFrame has 160 columns x 16k rows.

1 Answer 1

2

Create new columns names by list comprehension and then join to original:

df1 = df.loc[:,'B':'D'].multiply(df['A'], axis="index")
df1.columns = ['R{}'.format(x) for x in range(1, len(df1.columns) + 1)]

df = df.join(df1)
print (df)
     A    B    C    Z    R1   R2
0  2.0  8.0  1.0  5.0  16.0  2.0
1  3.0  9.0  0.0  4.0  27.0  0.0
2  4.0  9.0  0.0  3.0  36.0  0.0
3  5.0  8.0  1.0  2.0  40.0  5.0
4  6.0  8.0  0.0  1.0  48.0  0.0
5  7.0  9.0  1.0  0.0  63.0  7.0
Sign up to request clarification or add additional context in comments.

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.