Slicing numpy array taking every nth element - python

I have an numpy array of shape 24576x25 and i want to extract 3 array out of it. Where the first array contains the every 1st,4th,7th,10th,... element
while second array contains 2nd,5,8,11th,... element and third array with 3rd,6,9,12th,...
The output array sizes would be 8192x25.
I was doing the following in MATLAB
c = reshape(a,1,[]);
x = c(:,1:3:end);
y = c(:,2:3:end);
z = c(:,3:3:end);
I have tried a[:,0::3] in python but this works only if i have array of shape divisible by 3. What can i do?
X,Y = np.mgrid[0:24576:1, 0:25:1]
a = X[:,::,3]
b = X[:,1::3]
c = X[:,2::3]
does not work either. I need a,b,c.shape = 8192x25

A simple tweak to your original attempt should yield the results you want:
X,Y = np.mgrid[0:24576:1, 0:25:1]
a = X[0::3,:]
b = X[1::3,:]
c = X[2::3,:]

import numpy as np
a = np.arange(24576*25).reshape((24576,25))
a[::3]
a[::3].shape gives you (8192, 25)

Related

Extracting elements from a 1D array. Getting error invalid index to scalar variable

I have to extract elements from a 1D array and write a file.
import numpy as np
k0 =78
tpts = 10
x_mirror = [1,2,3,4,5,6,7,8,9,10]
alpha = -3
x_start = 3
u0 = []
for p in range(0,tpts): #initial condition at t = 0
ts = ((np.exp(alpha*((x_mirror[p]-x_start)**2))*(np.cos(k0*(x_mirror[p]-x_start)))))
u0.append(ts)
u0_array = np.array(u0)[np.newaxis]
u0_array_transpose = np.transpose(u0_array)
matrix_A = np.zeros((tpts,tpts))
matrix_A[tpts-1][tpts-1] = 56
matrixC = matrix_A # u0_array_transpose
matrixC2 = matrix_A # u0
u_pre = np.array(np.zeros(tpts))
print(u0_array)
In this I want to extract suppose elements of u0_array separately. I get my u0_array as [[ 2.89793185e-06 -4.27075012e-02 1.00000000e+00 -4.27075012e-02 2.89793185e-06 9.14080657e-14 -7.91091805e-22 2.42062877e-33 -1.24204313e-47 1.15841796e-64]]. This is just for example. How can I get different elements of u0_array? By using u0[][], I am getting error. Any help is highly appreciated.
u0_array is an array that contains an array of floats. To index an individual element, use u0_array[0][(index to access)]. You can also use .flatten(), as the comment states.

Numpy is not swapping elements

I am trying to swap two indices in the 2D array of NumPy. Unfortunately, only one element is getting swapped. Here is the code:
n = len(A)
perMatrix = np.zeros((n,n))
np.fill_diagonal(perMatrix, 1)
perMatrix = A
# swapping the row
print(perMatrix)
temp = perMatrix[switchIndex1]
print(temp)
# perMatrix[switchIndex1][0] = 14
perMatrix[switchIndex1], perMatrix[switchIndex2] = perMatrix[switchIndex2], perMatrix[switchIndex1]
print(perMatrix)
Here's what the code is outputting:
You could just add (on the line after perMatrix is created):
sigma = [switchIndex1, switchIndex2]
tau = [switchIndex2, switchIndex1]
perMatrix[sigma,:] = perMatrix[tau,:]

How to shuffle only row index in numpy arrays?

I have two numpy arrays.I want to shuffle only their row index simultaneously. Although I equalize their row index then when i shuffle a why it doesn't automatically shuffled b
a = np.arange(100).reshape(10,10)
b = np.arange(10).reshape(10,1)
a.shape[0]==b.shape[0]
np.random.shuffle(a)
print a
print b
It makes no sense, what you want to do can be down like below:
a = np.arange(100).reshape(10,10)
b = np.arange(10).reshape(10,1)
p = np.random.permutation(a.shape[0])
a = a[p]
b = b[p]
print a
print b
You can't marry two numpy arrays that way, to force them to stay in the same order. What you can do is save the order in a separate array and then sort both of them by it.
a = np.arange(100).reshape(10,10)
b = np.arange(10).reshape(10,1)
i = np.random.shuffle(np.arange(a.size[0]))
print a[i]
print b[i]
Use numpy.random.permutation:
import numpy as np
a = np.arange(100).reshape(10,10)
b = np.arange(10).reshape(10,1)
perm = np.random.permutation(a.shape[0])
print(a[perm, :])
print(b[perm, :])
While numpy.random.shuffle sorts the array in-place, in the last two lines of my code there is only a so called view of the arrays a and b created. If you check a and b afterwards, they are still the same. So if you want to use the shuffled version you should use something like a = a[perm, :] or c = (a[perm, :]).copy().

Selecting a second array based on the first one

Let's say I have two arrays of len(1000) each
array_a = np.array([1,2,3,....,1000]) # length of 1000
array_b = np.array([32344,83242,94323,....,48984]) # length of 1000
Now I select a subset of array_a based on certain conditions:
subset_a = array_a[(array_a>10) * (array_a<500)]
Now how do I select those values of array_b that belong to the above subset_a ?
I tried
subset_b = array_b[subset_a]
but I get an error
IndexError: arrays used as indices must be of integer (or boolean) type
Are you looking for this?
import numpy as np
array_a = np.array([1,2,3,4,5]) # length of 5
array_b = np.array([6,7,8,9,10]) # length of 5
condition = array_a>3
print condition
subset_a = array_a[condition]
print subset_a
subset_b = array_b[condition]
print subset_b
http://ideone.com/dAFLYL

filling numpy array by index

I have a function which gives me the index for a given value. Eg,
def F(value):
index = do_something(value)
return index
I want to use this index to fill a huge numpy array by 1s. Lets call array features
l = [1,4,2,3,7,5,3,6,.....]
NOTE: features.shape[0] = len(l)
for i in range(features.shape[0]):
idx = F(l[i])
features[i, idx] = 1
Is there a pythonic way to perform this (as the loop takes a lot of time if the array is huge)?
If you can vectorize F(value) you could write something like
indices = np.arange(features.shape[0])
feature_indices = F(l)
features.flat[indices, feature_indices] = 1
try this:
i = np.arange(features.shape[0]) # rows
j = np.vectorize(F)(np.array(l)) # columns
features[i,j] = 1

Categories

Resources