Ad
Appending Powers Of A Row At The And Of The Same Row In Numpy Matrix
I have a numpy matrix in. I want to append the second power, third power, ..., nth power of the row to the end of the row. For instance,
my_array = [
[1,2,3],
[2,3,4],
[3,4,5],
]
If n is 3, then my_array should be the following
my_array = [
[1,2,3,1,4,9,1,8,27],
[2,3,4,4,9,16,8,27,64],
[3,4,5,9,15,25,27,64,125]
]
I can do this manually as follows: (please do not consider the dimensions below, I know they are not correct for the example)
data_poly=np.ones((209,22))
data_poly[:,0:8]=data
data_poly[:,8]=data[:,1]**2
data_poly[:,9]=data[:,2]**2
data_poly[:,10]=data[:,3]**2
data_poly[:,11]=data[:,4]**2
data_poly[:,12]=data[:,5]**2
data_poly[:,13]=data[:,6]**2
data_poly[:,14]=data[:,7]**2
data_poly[:,15]=data[:,1]**3
data_poly[:,16]=data[:,2]**3
data_poly[:,17]=data[:,3]**3
data_poly[:,18]=data[:,4]**3
data_poly[:,19]=data[:,5]**3
data_poly[:,20]=data[:,6]**3
data_poly[:,21]=data[:,7]**3
How can I automize this process?
Ad
Answer
Here is one option using broadcasting, there is probably a smarter way to reshape:
N = 3
(my_array[...,None]**(np.arange(N)+1)).swapaxes(1,2).reshape(my_array.shape[0],-1)
or using tile
/repeat
:
N = 3
np.tile(my_array, N)**np.repeat(np.arange(N)+1, N)
output:
array([[ 1, 2, 3, 1, 4, 9, 1, 8, 27],
[ 2, 3, 4, 4, 9, 16, 8, 27, 64],
[ 3, 4, 5, 9, 16, 25, 27, 64, 125]])
input:
my_array = np.array([[1,2,3],
[2,3,4],
[3,4,5]])
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad