0

I have a dataframe like:

import pandas as pd
import numpy as np

d = {'col1': [[1,2,3]]}
df = pd.DataFrame(d)

Now lets say I want to create two new columns, squared and cubed like:


df['squared'] = [np.array([i**2 for i in x]) for x in df['col1']]
df['cubed'] = [np.array([i**3 for i in x]) for x in df['col1']]

df
        col1   squared      cubed
0  [1, 2, 3] [1, 4, 9] [1, 8, 27]

Now I would want to do element-wise multiplication and sum with each element of the squared and cubed numpy arrays. How could I go about doing this an an efficient manner (if say I had a large amount of data?)

1 Answer 1

1

You could try matrix multiplication.

df.apply(lambda x: x['squared'] @ x['cubed'], axis=1)
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think I've seen @ used in this context. Is this a Pandas or Numpy feature? I really like it.
It's available in both actually, but most people aren't aware it's been part of Python since I believe 3.5. But in this case numpy

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.