Remove square brackets in Python - python

I have this ouptut:
[[[-0.015, -0.1533, 1. ]]
[[-0.0069, 0.1421, 1. ]]
...
[[ 0.1318, -0.4406, 1. ]]
[[ 0.2059, -0.3854, 1. ]]]
But I would like to remove the square brackets that are leftover resulting as this:
[[-0.015 -0.1533 1. ]
[-0.0069 0.1421 1. ]
...
[ 0.1318 -0.4406 1. ]
[ 0.2059 -0.3854 1. ]]
My code is this:
XY = []
for i in range(4000):
Xy_1 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 1]
Xy_0 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 0]
Xy.append(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85)))
Xy = np.asarray(Xy)

You can use numpy.squeeze to remove 1 dim from array
>>> np.squeeze(Xy)
array([[ 0.3609, 0.2378, 0. ],
[-0.2432, -0.2043, 1. ],
[ 0.3081, -0.2457, 1. ],
...,
[ 0.311 , 0.03 , 1. ],
[-0.0572, -0.317 , 1. ],
[ 0.3026, 0.1829, 1. ]])
Or
reshape usingnumpy.reshape
>>> Xy.reshape(4000,3)
array([[ 0.3609, 0.2378, 0. ],
[-0.2432, -0.2043, 1. ],
[ 0.3081, -0.2457, 1. ],
...,
[ 0.311 , 0.03 , 1. ],
[-0.0572, -0.317 , 1. ],
[ 0.3026, 0.1829, 1. ]])
>>>

Try extend method.
Xy.extend(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85)))

You can use this one random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85))[0]
XY = []
for i in range(4000):
Xy_1 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 1]
Xy_0 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 0]
# Pythonic way :-)
Xy.append(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85))[0])
Xy = np.asarray(Xy)
print(Xy)
Output
[[ 0.3948 0.0915 1. ]
[ 0.4197 -0.344 1. ]
[-0.4541 0.3192 1. ]
[ 0.3285 0.0453 1. ]
[-0.0171 -0.3088 1. ]
[ 0.2958 -0.2757 1. ]
[-0.1303 0.1581 0. ]
[-0.4146 -0.4454 1. ]
[ 0.0247 0.325 1. ]
[-0.227 0.139 1. ]]

You can try this to remove 1dim using sum.
a=[ [[-0.015, -0.1533, 1. ]],
[[-0.0069, 0.1421, 1. ]],
...
[[ 0.1318, -0.4406, 1. ]],
[[ 0.2059, -0.3854, 1. ]] ]
sum(a,[])
'''
[[-0.015, -0.1533, 1. ],
[-0.0069, 0.1421, 1. ],
...
[ 0.1318, -0.4406, 1. ],
[ 0.2059, -0.3854, 1. ]]
'''

Related

How to use all the elements of the array using for loop?

actually, I need to put the returned values of the function (global_displacement(X)) into another running loop.
can someone please tell me how to obtain the required output?
and what idiotic mistake I have been doing.
as every time it gives me only the first([ 0, 0, X[0], X[1]]) OR
the last value([ X[20], X[21], X[53], X[54]]) in the output,
because of wrong indendation of "return j" in the below written code .
import numpy as np
X = [ 0.19515612, 0.36477665, 0.244737, 0.42873321, 0.16864666, 0.08636661, 0.05376605, -0.57201897, -0.00935055, -1.24923862, 0., -1.53111525, 0.00935055, -1.24923862, -0.05376605, -0.57201897, -0.1686466,
0.08636661, -0.244737, 0.42873321, -0.19515612, 0.36477665, 0.02279911, 0. , 0.3563355 , 0.01379104, 0. , 0.42289958, -0.00747999, 0. , 0.0825908, -0.02949519 , 0. , -0.57435396,
-0.04074819, 0. , -1.25069528 ,-0.02972642, 0. , -1.53227704, -0. , 0. , -1.25069528 , 0.02972642 , 0. , -0.57435396 , 0.04074819 , 0. , 0.0825908, 0.02949519, 0. ,
0.42289958, 0.00747999 , 0. , 0.3563355 , -0.01379104, -0.02279911]
def global_displacement(X):
global_displacements = np.array( [[ 0, 0, X[0], X[1]], [ X[0], X[1], X[2], X[3]], [ X[2], X[3],X[4], X[5]], [ X[4],X[5],X[6], X[7]],[ X[6],X[7],X[8],X[9]], [ X[8],X[9],X[10], X[11] ], [ X[10], X[11],X[12], X[13]], [ X[12], X[13],X[14], X[15]],[ X[14], X[15],X[16], X[17]],[ X[16], X[17],X[18], X[19]], [ X[18], X[19],X[20], X[21]],[ X[20], X[21], 0, 0],
[ X[0], X[1], X[23], X[24]], [ X[2], X[3], X[26],X[27]], [ X[4], X[5], X[29],X[30]], [ X[6], X[7], X[32],X[33]], [ X[8],X[9],X[35], X[36]], [ X[10], X[11], X[38], X[39]], [ X[12], X[13], X[41], X[42]] ,[ X[14], X[15], X[44], X[45]],[ X[16], X[17], X[47], X[48]],[ X[18], X[19], X[50], X[51]], [ X[20], X[21], X[53], X[54]] ] )
for i in (global_displacements):
j = i.reshape(4,1)
return j
print(global_displacement(X))
this is the expected output, and I need to put these values in another loop, by calling this function.
[[0. ]
[0. ]
[0.19515612]
[0.36477665]]
[[0.19515612]
[0.36477665]
[0.244737 ]
[0.42873321]]
[[0.244737 ]
[0.42873321]
[0.16864666]
[0.08636661]]
[[ 0.16864666]
[ 0.08636661]
[ 0.05376605]
[-0.57201897]]
[[ 0.05376605]
[-0.57201897]
[-0.00935055]
[-1.24923862]]
[[-0.00935055]
[-1.24923862]
[ 0. ]
[-1.53111525]]
[[ 0. ]
[-1.53111525]
[ 0.00935055]
[-1.24923862]]
[[ 0.00935055]
[-1.24923862]
[-0.05376605]
[-0.57201897]]
[[-0.05376605]
[-0.57201897]
[-0.1686466 ]
[ 0.08636661]]
[[-0.1686466 ]
[ 0.08636661]
[-0.244737 ]
[ 0.42873321]]
[[-0.244737 ]
[ 0.42873321]
[-0.19515612]
[ 0.36477665]]
[[-0.19515612]
[ 0.36477665]
[ 0. ]
[ 0. ]]
[[0.19515612]
[0.36477665]
[0. ]
[0.3563355 ]]
[[0.244737 ]
[0.42873321]
[0. ]
[0.42289958]]
[[0.16864666]
[0.08636661]
[0. ]
[0.0825908 ]]
[[ 0.05376605]
[-0.57201897]
[ 0. ]
[-0.57435396]]
[[-0.00935055]
[-1.24923862]
[ 0. ]
[-1.25069528]]
[[ 0. ]
[-1.53111525]
[ 0. ]
[-1.53227704]]
[[ 0.00935055]
[-1.24923862]
[ 0. ]
[-1.25069528]]
[[-0.05376605]
[-0.57201897]
[ 0. ]
[-0.57435396]]
[[-0.1686466 ]
[ 0.08636661]
[ 0. ]
[ 0.0825908 ]]
[[-0.244737 ]
[ 0.42873321]
[ 0. ]
[ 0.42289958]]
[[-0.19515612]
[ 0.36477665]
[ 0. ]
[ 0.3563355 ]]
Your function already converts everything into the right format except that the inner values should be stored into a list. For this you can use numpy.newaxis. It is used to add a new dimension to your array (good post about its functionality).
import numpy as np
def global_displacement(X):
global_displacements = np.array( [[ 0, 0, X[0], X[1]], [ X[0], X[1], X[2], X[3]], [ X[2], X[3],X[4], X[5]], [ X[4],X[5],X[6], X[7]],[ X[6],X[7],X[8],X[9]], [ X[8],X[9],X[10], X[11] ], [ X[10], X[11],X[12], X[13]], [ X[12], X[13],X[14], X[15]],[ X[14], X[15],X[16], X[17]],[ X[16], X[17],X[18], X[19]], [ X[18], X[19],X[20], X[21]],[ X[20], X[21], 0, 0],
[ X[0], X[1], X[23], X[24]], [ X[2], X[3], X[26],X[27]], [ X[4], X[5], X[29],X[30]], [ X[6], X[7], X[32],X[33]], [ X[8],X[9],X[35], X[36]], [ X[10], X[11], X[38], X[39]], [ X[12], X[13], X[41], X[42]] ,[ X[14], X[15], X[44], X[45]],[ X[16], X[17], X[47], X[48]],[ X[18], X[19], X[50], X[51]], [ X[20], X[21], X[53], X[54]] ] )
new_structure = global_displacements[:, :, np.newaxis]
return new_structure
X = [ 0.19515612, 0.36477665, 0.244737, 0.42873321, 0.16864666, 0.08636661, 0.05376605, -0.57201897, -0.00935055, -1.24923862, 0., -1.53111525, 0.00935055, -1.24923862, -0.05376605, -0.57201897, -0.1686466,
0.08636661, -0.244737, 0.42873321, -0.19515612, 0.36477665, 0.02279911, 0. , 0.3563355 , 0.01379104, 0. , 0.42289958, -0.00747999, 0. , 0.0825908, -0.02949519 , 0. , -0.57435396,
-0.04074819, 0. , -1.25069528 ,-0.02972642, 0. , -1.53227704, -0. , 0. , -1.25069528 , 0.02972642 , 0. , -0.57435396 , 0.04074819 , 0. , 0.0825908, 0.02949519, 0. ,
0.42289958, 0.00747999 , 0. , 0.3563355 , -0.01379104, -0.02279911]
result = global_displacement(X)
print(result)
Output:
[[[ 0. ]
[ 0. ]
[ 0.19515612]
[ 0.36477665]]
[[ 0.19515612]
[ 0.36477665]
[ 0.244737 ]
[ 0.42873321]]
[[ 0.244737 ]
[ 0.42873321]
[ 0.16864666]
[ 0.08636661]]
[[ 0.16864666]
[ 0.08636661]
[ 0.05376605]
[-0.57201897]]
[[ 0.05376605]
[-0.57201897]
[-0.00935055]
[-1.24923862]]
[[-0.00935055]
[-1.24923862]
[ 0. ]
[-1.53111525]]
[[ 0. ]
[-1.53111525]
[ 0.00935055]
[-1.24923862]]
[[ 0.00935055]
[-1.24923862]
[-0.05376605]
[-0.57201897]]
[[-0.05376605]
[-0.57201897]
[-0.1686466 ]
[ 0.08636661]]
[[-0.1686466 ]
[ 0.08636661]
[-0.244737 ]
[ 0.42873321]]
[[-0.244737 ]
[ 0.42873321]
[-0.19515612]
[ 0.36477665]]
[[-0.19515612]
[ 0.36477665]
[ 0. ]
[ 0. ]]
[[ 0.19515612]
[ 0.36477665]
[ 0. ]
[ 0.3563355 ]]
[[ 0.244737 ]
[ 0.42873321]
[ 0. ]
[ 0.42289958]]
[[ 0.16864666]
[ 0.08636661]
[ 0. ]
[ 0.0825908 ]]
[[ 0.05376605]
[-0.57201897]
[ 0. ]
[-0.57435396]]
[[-0.00935055]
[-1.24923862]
[ 0. ]
[-1.25069528]]
[[ 0. ]
[-1.53111525]
[ 0. ]
[-1.53227704]]
[[ 0.00935055]
[-1.24923862]
[ 0. ]
[-1.25069528]]
[[-0.05376605]
[-0.57201897]
[ 0. ]
[-0.57435396]]
[[-0.1686466 ]
[ 0.08636661]
[ 0. ]
[ 0.0825908 ]]
[[-0.244737 ]
[ 0.42873321]
[ 0. ]
[ 0.42289958]]
[[-0.19515612]
[ 0.36477665]
[ 0. ]
[ 0.3563355 ]]]
First off, you don't need .reshape to transform a 1D array of N elements into a 2D array that's N by 1. You can just add a dimension to the array.
Second, you generally don't want to write loops to handle a Numpy array. You want to use Numpy tools to process everything at once. Just think about the problem in the full number of dimensions: you want to transform a 2D array that's M by N, into a 3D one that's M by N by 1. That's... still just adding a dimension to the array.
So:
global_displacements = np.array(...)
return global_displacements[..., np.newaxis]

Floating point with normalized function

I write own normalized module, because I seem sklearn don't normalize all data together (only per column or row). And I have two codes.
First code with sklearn.
from sklearn import preprocessing
data = np.array([[-1], [-0.5], [0], [1], [2], [6], [10], [18]])
print(data)
scaler = preprocessing.MinMaxScaler(feature_range=(5, 10))
print(scaler.fit_transform(data))
print(scaler.inverse_transform(scaler.fit_transform(data)))
Result:
[[-1. ]
[-0.5]
[ 0. ]
[ 1. ]
[ 2. ]
[ 6. ]
[10. ]
[18. ]]
[[ 5. ]
[ 5.13157895]
[ 5.26315789]
[ 5.52631579]
[ 5.78947368]
[ 6.84210526]
[ 7.89473684]
[10. ]]
[[-1. ]
[-0.5]
[ 0. ]
[ 1. ]
[ 2. ]
[ 6. ]
[10. ]
[18. ]]
And with my module:
data = np.array([[-1, 2], [-0.5, 6], [0, 10], [1, 18]])
print(data)
scaler = scl.Scaler(feature_range=(5, 10))
print(scaler.transform(data))
print(scaler.inverse_transform(scaler.transform(data)))
Result:
[[-1. 2. ]
[-0.5 6. ]
[ 0. 10. ]
[ 1. 18. ]]
[[ 5. 5.78947368]
[ 5.13157895 6.84210526]
[ 5.26315789 7.89473684]
[ 5.52631579 10. ]]
[[-1.00000000e+00 2.00000000e+00]
[-5.00000000e-01 6.00000000e+00]
[ 1.33226763e-15 1.00000000e+01]
[ 1.00000000e+00 1.80000000e+01]]
I guess 1.33226763e-15 don't suit for me.
I think it occur because there is floating point. Although sklearn don't have this problem.
Please tell me where do I do mistake?
import numpy as np
class Scaler:
def __init__(self, feature_range: tuple = (0, 1)):
self.scaler_min = feature_range[0]
self.scaler_max = feature_range[1]
self.data_min = None
self.data_max = None
def transform(self, x: np.ndarray):
self.data_min = x.min(initial=0)
self.data_max = x.max(initial=0)
scaled_data = (x - x.min(initial=0)) / (x.max(initial=0) - x.min(initial=0))
return scaled_data * (self.scaler_max - self.scaler_min) + self.scaler_min
def inverse_transform(self, x: np.ndarray):
scaled_data = (x - self.scaler_min) / (self.scaler_max - self.scaler_min)
return scaled_data * (self.data_max - self.data_min) + self.data_min

How to scale each column of a matrix

This is how I scale a single vector:
vector = np.array([-4, -3, -2, -1, 0])
# pass the vector, current range of values, the desired range, and it returns the scaled vector
scaledVector = np.interp(vector, (vector.min(), vector.max()), (-1, +1)) # results in [-1. -0.5 0. 0.5 1. ]
How can I apply the above approach to each column of a given matrix?
matrix = np.array(
[[-4, -4, 0, 0, 0],
[-3, -3, 1, -15, 0],
[-2, -2, 8, -1, 0],
[-1, -1, 11, 12, 0],
[0, 0, 50, 69, 80]])
scaledMatrix = [insert code that scales each column of the matrix]
Note that the first two columns of the scaledMatrix should be equal to the scaledVector from the first example. For the matrix above, the correctly computed scaledMatrix is:
[[-1. -1. -1. -0.64285714 -1. ]
[-0.5 -0.5 -0.96 -1. -1. ]
[ 0. 0. -0.68 -0.66666667 -1. ]
[ 0.5 0.5 -0.56 -0.35714286 -1. ]
[ 1. 1. 1. 1. 1. ]]
My current approach (wrong):
np.interp(matrix, (np.min(matrix), np.max(matrix)), (-1, +1))
If you want to do it by hand and understand what's going on:
First substract columnwise mins to make each columns have min 0.
Then divide by columnwise amplitude (max - min) to make each column have max 1.
Now each column is between 0 and 1. If you want it to be between -1 and 1, multiply by 2, and substract 1:
In [3]: mins = np.min(matrix, axis=0)
In [4]: maxs = np.max(matrix, axis=0)
In [5]: (matrix - mins[None, :]) / (maxs[None, :] - mins[None, :])
Out[5]:
array([[ 0. , 0. , 0. , 0.17857143, 0. ],
[ 0.25 , 0.25 , 0.02 , 0. , 0. ],
[ 0.5 , 0.5 , 0.16 , 0.16666667, 0. ],
[ 0.75 , 0.75 , 0.22 , 0.32142857, 0. ],
[ 1. , 1. , 1. , 1. , 1. ]])
In [6]: 2 * _ - 1
Out[6]:
array([[-1. , -1. , -1. , -0.64285714, -1. ],
[-0.5 , -0.5 , -0.96 , -1. , -1. ],
[ 0. , 0. , -0.68 , -0.66666667, -1. ],
[ 0.5 , 0.5 , -0.56 , -0.35714286, -1. ],
[ 1. , 1. , 1. , 1. , 1. ]])
I use [None, :] for numpy to understand that I'm talking about "row vectors", not column ones.
Otherwise, use the wonderful sklearn package, whose preprocessing module has lots of useful transformers:
In [13]: from sklearn.preprocessing import MinMaxScaler
In [14]: scaler = MinMaxScaler(feature_range=(-1, 1))
In [15]: scaler.fit(matrix)
Out[15]: MinMaxScaler(copy=True, feature_range=(-1, 1))
In [16]: scaler.transform(matrix)
Out[16]:
array([[-1. , -1. , -1. , -0.64285714, -1. ],
[-0.5 , -0.5 , -0.96 , -1. , -1. ],
[ 0. , 0. , -0.68 , -0.66666667, -1. ],
[ 0.5 , 0.5 , -0.56 , -0.35714286, -1. ],
[ 1. , 1. , 1. , 1. , 1. ]])

How to get random forest regression performance output in Python like that produced in R?

In R, I can easily get the performance of a random forest like the following.
How can I get the similar stuff in Python easily? Thanks a lot.
Summary of the Random Forest Model
==================================
Number of observations used to build the model: 35
Missing value imputation is active.
Call:
randomForest(formula = rank ~ .,
data = crs$dataset[crs$sample, c(crs$input, crs$target)],
ntree = 500, mtry = 3, importance = TRUE, replace = FALSE, na.action = na.roughfix)
Type of random forest: regression
Number of trees: 500
No. of variables tried at each split: 3
Mean of squared residuals: 5.578147
% Var explained: 97.22
Variable Importance
Here there is a simple example using sklearn random forest . http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier
You can easily get the values that you are looking for.
In this example we are using an input matrix X with 2 variables and a binary output y.
from sklearn.ensemble import RandomForestClassifier
fr = RandomForestClassifier(n_estimators=100, oob_score=True).fit(X, y)
fr.n_estimators
Out[10]: 100
fr.oob_decision_function_
Out[11]:
array([[ 0.14285714, 0.85714286],
[ 0.86666667, 0.13333333],
[ 0.02631579, 0.97368421],
[ 1. , 0. ],
[ 0.97826087, 0.02173913],
[ 0.97826087, 0.02173913],
[ 0.20512821, 0.79487179],
[ 0.97368421, 0.02631579],
[ 0.77777778, 0.22222222],
[ 0. , 1. ],
[ 0. , 1. ],
[ 1. , 0. ],
[ 0.52380952, 0.47619048],
[ 0.43243243, 0.56756757],
[ 1. , 0. ],
[ 0. , 1. ],
[ 0.05714286, 0.94285714],
[ 0. , 1. ],
[ 1. , 0. ],
[ 0.76470588, 0.23529412],
[ 1. , 0. ],
[ 0. , 1. ],
[ 0.95454545, 0.04545455],
[ 0.9 , 0.1 ],
[ 0.02222222, 0.97777778],
[ 0.875 , 0.125 ],
[ 0.02857143, 0.97142857],
[ 1. , 0. ],
[ 0.58823529, 0.41176471],
[ 0. , 1. ],
[ 0.20512821, 0.79487179],
[ 0.97435897, 0.02564103],
[ 0.91176471, 0.08823529],
[ 0. , 1. ],
[ 0.30232558, 0.69767442],
[ 1. , 0. ],
[ 0.94444444, 0.05555556],
[ 0. , 1. ],
[ 0.075 , 0.925 ],
[ 0.05263158, 0.94736842],
[ 1. , 0. ],
[ 0. , 1. ],
[ 0.02702703, 0.97297297],
[ 0.91176471, 0.08823529],
[ 0.43243243, 0.56756757],
[ 0.08333333, 0.91666667],
[ 0.10526316, 0.89473684],
[ 0.93548387, 0.06451613],
[ 0.02857143, 0.97142857],
[ 0.53658537, 0.46341463],
[ 0.5 , 0.5 ],
[ 0.66666667, 0.33333333],
[ 1. , 0. ],
[ 0.55555556, 0.44444444],
[ 0.96666667, 0.03333333],
[ 0.97142857, 0.02857143],
[ 0. , 1. ],
[ 0. , 1. ],
[ 1. , 0. ],
[ 0.05882353, 0.94117647],
[ 0.94594595, 0.05405405],
[ 0.11904762, 0.88095238],
[ 0.92307692, 0.07692308],
[ 0.69767442, 0.30232558],
[ 1. , 0. ],
[ 0.12121212, 0.87878788],
[ 1. , 0. ],
[ 0.97727273, 0.02272727],
[ 1. , 0. ],
[ 0.87878788, 0.12121212],
[ 0.02380952, 0.97619048],
[ 0. , 1. ],
[ 0. , 1. ],
[ 0. , 1. ],
[ 0.10810811, 0.89189189],
[ 1. , 0. ],
[ 1. , 0. ],
[ 0.97619048, 0.02380952],
[ 0.54545455, 0.45454545],
[ 0.02380952, 0.97619048],
[ 0.07317073, 0.92682927],
[ 0.94285714, 0.05714286],
[ 0.25714286, 0.74285714],
[ 0. , 1. ],
[ 0. , 1. ],
[ 0.97560976, 0.02439024],
[ 0.11111111, 0.88888889],
[ 1. , 0. ],
[ 1. , 0. ],
[ 0.02857143, 0.97142857],
[ 0.97916667, 0.02083333],
[ 0. , 1. ],
[ 0.02564103, 0.97435897],
[ 0. , 1. ],
[ 0.32258065, 0.67741935],
[ 0.56410256, 0.43589744],
[ 1. , 0. ],
[ 0.92682927, 0.07317073],
[ 1. , 0. ],
[ 0.08823529, 0.91176471]])
fr.oob_score_
Out[12]: 0.87
fr.feature_importances_
Out[13]: array([ 0.82407373, 0.17592627])

Numpy: Fastest way of computing diagonal for each row of a 2d array

Given a 2d Numpy array, I would like to be able to compute the diagonal for each row in the fastest way possible, I'm right now using a list comprehension but I'm wondering if it can be vectorised somehow?
For example using the following M array:
M = np.random.rand(5, 3)
[[ 0.25891593 0.07299478 0.36586996]
[ 0.30851087 0.37131459 0.16274825]
[ 0.71061831 0.67718718 0.09562581]
[ 0.71588836 0.76772047 0.15476079]
[ 0.92985142 0.22263399 0.88027331]]
I would like to compute the following array:
np.array([np.diag(row) for row in M])
array([[[ 0.25891593, 0. , 0. ],
[ 0. , 0.07299478, 0. ],
[ 0. , 0. , 0.36586996]],
[[ 0.30851087, 0. , 0. ],
[ 0. , 0.37131459, 0. ],
[ 0. , 0. , 0.16274825]],
[[ 0.71061831, 0. , 0. ],
[ 0. , 0.67718718, 0. ],
[ 0. , 0. , 0.09562581]],
[[ 0.71588836, 0. , 0. ],
[ 0. , 0.76772047, 0. ],
[ 0. , 0. , 0.15476079]],
[[ 0.92985142, 0. , 0. ],
[ 0. , 0.22263399, 0. ],
[ 0. , 0. , 0.88027331]]])
Here's one way using element-wise multiplication of np.eye(3) (the 3x3 identity array) and a slightly re-shaped M:
>>> M = np.random.rand(5, 3)
>>> np.eye(3) * M[:,np.newaxis,:]
array([[[ 0.42527357, 0. , 0. ],
[ 0. , 0.17557419, 0. ],
[ 0. , 0. , 0.61920924]],
[[ 0.04991268, 0. , 0. ],
[ 0. , 0.74000307, 0. ],
[ 0. , 0. , 0.34541354]],
[[ 0.71464307, 0. , 0. ],
[ 0. , 0.11878955, 0. ],
[ 0. , 0. , 0.65411844]],
[[ 0.01699954, 0. , 0. ],
[ 0. , 0.39927673, 0. ],
[ 0. , 0. , 0.14378892]],
[[ 0.5209439 , 0. , 0. ],
[ 0. , 0.34520876, 0. ],
[ 0. , 0. , 0.53862677]]])
(By "re-shaped M" I mean that the rows of M are made to face out along the z-axis rather than across the y-axis, giving M the shape (5, 1, 3).)
Despite the good answer of #ajcr, a much faster alternative can be achieved with fancy indexing (tested in NumPy 1.9.0):
import numpy as np
def sol0(M):
return np.eye(M.shape[1]) * M[:,np.newaxis,:]
def sol1(M):
b = np.zeros((M.shape[0], M.shape[1], M.shape[1]))
diag = np.arange(M.shape[1])
b[:, diag, diag] = M
return b
where the timing shows this is approximately 4X faster:
M = np.random.random((1000, 3))
%timeit sol0(M)
#10000 loops, best of 3: 111 µs per loop
%timeit sol1(M)
#10000 loops, best of 3: 23.8 µs per loop

Categories

Resources