Home > Blockchain >  Make an array (1, x, x^2) based on x in dataframe
Make an array (1, x, x^2) based on x in dataframe

Time:11-17

Let's suppose that I have dataframe df similar like:

c0     c1  
10     2        
8      2         
4      1        

How can I make an np.array for each element of this datafrmae so that I have for each element array (1, x, x^2)?

For example for col1, first element (0) should get the array [1, 2, 4], for c0, for the fisrt elemend (10), get [1,10,100] etc.

The new np.array should then have the dimensions (2 x 3 x 3), 2 for two columns, 3 for 3 rows and 3 for 3 values [1,x,x^2]?

I tried:

df.loc[:,i].apply(lambda x: np.power(x,np.arange(3)))

But I could not get the wanted form of np.array (dimensions: 2 x 3 x 3).

CodePudding user response:

The numpy approach would be to broadcast to a 3D array:

out = df.to_numpy()[...,None]**[0,1,2]

Output:

array([[[  1,  10, 100],
        [  1,   2,   4]],

       [[  1,   8,  64],
        [  1,   2,   4]],

       [[  1,   4,  16],
        [  1,   1,   1]]])

If you want a (2, 3, 3) shape, swap the axes:

out = (df.to_numpy()[...,None]**[0,1,2]).swapaxes(0, 1)

output:

array([[[  1,  10, 100],
        [  1,   8,  64],
        [  1,   4,  16]],

       [[  1,   2,   4],
        [  1,   2,   4],
        [  1,   1,   1]]])
  • Related