Transpose of a matrix in numpy - arrays

I have this numpy array:
a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])
b is a transpose of a. I want b be like this:
b = np.array([[[1,-1],[2,-2],[3,-3]],[[4,-4],[5,-5],[6,-6]]])
Is it possible to do it in one line?
EDIT:
And if I have this instead:
a = np.empty(3,dtype = object)
a[0] = np.array([[1,2,3],[-1,-2,-3]])
a[1] = np.array([[4,5,6],[-4,-5,-6]])
How can I get b?

You can do it using np.transpose(a,(0,2,1)):
In [26]: a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])
In [27]: b = np.transpose(a,(0,2,1))
In [28]: print a
[[[ 1 2 3]
[-1 -2 -3]]
[[ 4 5 6]
[-4 -5 -6]]]
In [29]: print b
[[[ 1 -1]
[ 2 -2]
[ 3 -3]]
[[ 4 -4]
[ 5 -5]
[ 6 -6]]]
For your edited question with an array of dtype=object -- there is no direct way to compute the transpose, because numpy doesn't know how to transpose a generic object. However, you can use list comprehension and transpose each object separately:
In [90]: a = np.empty(2,dtype = object)
In [91]: a[0] = np.array([[1,2,3],[-1,-2,-3]])
In [92]: a[1] = np.array([[4,5,6],[-4,-5,-6]])
In [93]: print a
[[[ 1 2 3]
[-1 -2 -3]] [[ 4 5 6]
[-4 -5 -6]]]
In [94]: b = np.array([np.transpose(o) for o in a],dtype=object)
In [95]: print b
[[[ 1 -1]
[ 2 -2]
[ 3 -3]]
[[ 4 -4]
[ 5 -5]
[ 6 -6]]]

Related

NumPy Slicing HackerRank

I have wrote a function named array_slice which gets four numbers n, n_dim, n_row, n_col from the user and performs array operations given below.
Instructions:
Create an array x of shape (n_dim, n_row, n_col), having first n natural numbers.
Create a Boolean array b of shape (2,).
Print the values for following expressions: x[b] and x[b,:,1:3]
For example if we have input 30, 2, 3, 5, for each corresponding parameters n, n_dim, n_row, n_col, Then the output prints will be as:
[[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14]]]
[[[ 1 2] [ 6 7] [11 12]]]
The written code is:
import numpy as np
# Enter your code here. Read input from STDIN. Print output to STDOUT
def array_slice(n,n_dim,n_row,n_col):
x=np.array(n, dtype=int, ndmin=n_dim).reshape(n_row,n_col)
b=np.array([True,False],dtype="bool",ndmin=n_dim).reshape(2,)
print(x[b])
print(x[b,:,1:3])
if __name__ == '__main__':
n = int(input())
n_dim = int(input())
n_row = int(input())
n_col = int(input())
array_slice(n,n_dim,n_row,n_col)
I went through official documentation NumPy, but still couldn't understand the error. I tried all possible ways with arange and array but I'm unable to get solution. Please help me out
This passed all test cases:
x = np.arange(n, dtype=int).reshape(n_dim, n_row, n_col)
b = np.array([True, False], dtype="bool", ndmin=n_dim).reshape(2,)
print(x[b])
print(x[b, :, 1:3])
I have tried the following code for x array using np.arrange:
x = np.arange(n, dtype=int).reshape(n_dim, n_row, n_col)
it will work:
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]]
[[[ 1 2]
[ 6 7]
[11 12]]]

subtracting every nth array with every nth array

I have an array with the shape (10000,6). For example:
a = np.array([[5, 5, 5, 5, 5, 5][10, 10, 10, 10, 10][15, 15, 15, 15, 15]...])
I want to take every 25th array and subtract its element values from the next 25 elements until a new subtraction array in selected. so for example if the first array is:
[10, 10, 10, 10, 10]
then these values should be subtracted on the array itself and the next 25 arrays until for example a new subtraction array like this is selected:
[2, 2, 2, 2, 2]
then the array itself and the following 25 elements should be subtracted that arrays values.
This means that after the operation every 25th array will be:
[0, 0, 0, 0, 0]
because it has been subtracted by itself.
Here's what I would do:
import numpy as np
arr = np.random.randint(0, 10, (9, 3))
group_size = 3
# select vectors you want ot subtract and copy them {group_size} times
selected = arr[::group_size].repeat(3, axis = 0)
# subtract selected vectors from all vectors in the group
sub_arr = arr-selected
output:
arr =
[[9 6 3]
[8 3 3]
[2 0 4]
[0 3 9]
[3 9 9]
[0 8 6]
[4 0 0]
[6 1 9]
[2 6 4]]
selected =
[[9 6 3]
[9 6 3]
[9 6 3]
[0 3 9]
[0 3 9]
[0 3 9]
[4 0 0]
[4 0 0]
[4 0 0]]
sub_arr =
[[ 0 0 0]
[-1 -3 0]
[-7 -6 1]
[ 0 0 0]
[ 3 6 0]
[ 0 5 -3]
[ 0 0 0]
[ 2 1 9]
[-2 6 4]]
You can reshape your array so that each chunk has the right number of lines, and then simply subtract the first line
import numpy as np
a = np.arange(10000)[:, None] * np.ones(6)
a = a.reshape(-1, 25, 6)
a -= a[:, 0, :][:, None, :]
a = a.reshape(-1, 6)

Julia, use findall to reset a third row in a 3d array

I'm attempting to use findall to get an index of which elements of one 1d array are greater than those of a second 1d array, and then use those indexes to set corresponding values of a third 1d array to 0.
MWE:
# create 3d array
a, b = [3;2;2], [4;3;2];
c = transpose(cat(a,b, dims = 2));
d, e = [1;2;3], [2;3;4];
f = transpose(cat(d,e, dims = 2));
g = cat(c, f, dims = 3);
g
2×3×2 Array{Int64,3}:
[:, :, 1] =
3 2 2
4 3 2
[:, :, 2] =
1 2 3
2 3 4
findall.(g[end,:,1] >= g[end-1,:,1])
and use indexes to reset elements of g[end,:,2] such that I end up with
g
2×3×2 Array{Int64,3}:
[:, :, 1] =
3 2 2
4 3 2
[:, :, 2] =
1 2 3
0 0 4
Thx. J
The code below gives the answer you request. You just have the . in the wrong spot. You want to compare the > operation element by element, and then apply findall to the entire resulting array (not element by element).
julia> g[end, findall(g[end,:,1] .> g[end-1,:,1]), 2] .= 0
2-element view(::Array{Int64,3}, 2, [1, 2], 2) with eltype Int64:
0
0
julia> g
2×3×2 Array{Int64,3}:
[:, :, 1] =
3 2 2
4 3 2
[:, :, 2] =
1 2 3
0 0 4
However, I wouldn't try to compile all your data into one big array like that. It would be easier to use three separate 1D array variables than three dimensions in one variable. Again using your variables above:
julia> e[b .> a] .= 0
2-element view(::Array{Int64,1}, [1, 2]) with eltype Int64:
0
0
julia> e
3-element Array{Int64,1}:
0
0
4

Tensorflow : Get indices of array rows which are zero

For a tensor
[[1 2 3 1]
[0 0 0 0]
[1 3 5 7]
[0 0 0 0]
[3 5 7 8]]
how can I get the indices of the 0 rows? I.e. the list [1,3], in Tensorflow?
As far as I know, you can't really do that in one command like you would with a more advanced library like NumPy.
If you really want to use TF functions I could suggest a few like:
x = tf.Variable([
[1,2,3,1],
[0,0,0,0],
[1,3,5,7],
[0,0,0,0],
[3,5,7,8]])
y = tf.Variable([0,0,0,0])
condition = tf.equal(x, y)
indices = tf.where(condition)
This would result the following:
[[1 0]
[1 1]
[1 2]
[1 3]
[3 0]
[3 1]
[3 2]
[3 3]]
Or you could use the following if you just want to get only the zero lines:
row_wise_sum = tf.reduce_sum(tf.abs(x),1)
select_zero_sum = tf.where(tf.equal(row_wise_sum,0))
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(sess.run(select_zero_sum))
The result being:
[[1]
[3]]
It can be done in an easier way too:
g = tf.Graph()
with g.as_default():
a = tf.placeholder(dtype=tf.float32, shape=[3, 4])
b = tf.placeholder(dtype=tf.float32, shape=[1, 4])
res = tf.not_equal(a, b)
res = tf.reduce_sum(tf.cast(res, tf.float32), 1)
res = tf.where(tf.equal(res1, [0.0]))[0]
with tf.Session(graph=g) as sess:
sess.run(tf.global_variables_initializer())
dict_ = {
a:np.array([[2.0,6.0,3.0,2.0],
[1.0,8.0,32.0,1.0],
[1.0,8.0,3.0,11.0]]),
b:np.array([[1.0,8.0,3.0,11.0]])
}
print(sess.run(res, feed_dict=dict_))
:[2]

Generating matlab array from union and replacement of two arrays

I have two large arrays which I will illustrate using the following examples.
The first array A is:
[ 1 21;
3 4;
4 12;
5 65 ];
The second array B is:
[ 3 56;
5 121];
I want to obtain the final array C as following:
[ 1 21;
3 56;
4 12;
5 121 ];
i.e. replace second column of A with elements of B when available.
I am using Matlab 2007.
MATLAB Solution
With ismember -
C = A;
[is_present,pos] = ismember(A(:,1),B(:,1))
C(is_present,2) = B(pos(is_present),2)
Or use bsxfun to replace ismember -
[is_present,pos] = max(bsxfun(#eq,A(:,1),B(:,1).'),[],2);
Sample run -
>> A,B
A =
1 21
3 4
4 12
5 65
B =
3 56
5 121
4 66
>> C = A;
[is_present,pos] = ismember(A(:,1),B(:,1));
C(is_present,2) = B(pos(is_present),2);
>> C
C =
1 21
3 56
4 66
5 121
Bonus: NUMPY/PYTHON Solution
You can use boolean indexing with np.in1d -
import numpy as np
mask = np.in1d(A[:,0],B[:,0])
C = A.copy()
C[mask] = B
Sample run -
In [34]: A
Out[34]:
array([[ 1, 21],
[ 3, 4],
[ 4, 12],
[ 5, 65]])
In [35]: B
Out[35]:
array([[ 3, 56],
[ 5, 121]])
In [36]: mask = np.in1d(A[:,0],B[:,0])
...: C = A.copy()
...: C[mask] = B
...:
In [37]: C
Out[37]:
array([[ 1, 21],
[ 3, 56],
[ 4, 12],
[ 5, 121]])

Resources