I've got a function that needs to add a column at the start of a given matrix. I've got it working:
def add_ones(X):
return np.vstack((np.ones(X.shape[0]), X.T)).T
This works, but as you can see, it transposes the matrix twice. I tried it first without transposing the matrix, but it seems that np.ones(m) always produces a row vector that I couldn't transpose (I tried doing np.ones(m).T).
My question is, is there a better way to do this? I'm not very familiar with numpy and have no idea of the performance downfalls of transposing a matrix.
You can use np.concatenate -
np.concatenate((np.ones((X.shape[0],1)),X),axis=1)
You can also use np.column_stack -
np.column_stack((np.ones((X.shape[0])),X))
Final one with np.hstack -
np.hstack((np.ones((X.shape[0],1)),X))
You can add a column using the c_.
np.c_[np.ones(X.shape[0]), X]
http://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html
Related
If I have an array like this
arr=np.array([['a','b','c'],
['d','e','f']])
and an array of booleans of the same shape, like this:
boolarr=np.array([[False,True,False],
[True,True,True]])
I want to be able to only select the elements from the first array, that correspond to a True in the boolean array. So the output would be:
out=[['b'],
['d','e','f']]
I managed to solve this with a simple for loop
out=[]
for n, i in enumerate(arr):
out.append(i[boolarr[n]])
out=np.array(out)
but the problem is this solution is slow for large arrays, and was wondering if there was an easier solution with numpys indexing. Just using the normal notation arr[boolarr] returns a single flat array ['b','d','e','f']. I also tried using a slice with arr[:,[True,False,True]], which keeps the shape but can only use one boolean array.
Thanks for the comments. I misunderstood how an array works. For those curious this is my solution (I'm actually working with numbers):
arr[boolarr]=np.nan
And then I just changed how the rest of the function handles nan values
I couldn't seem to find this problem on stackoverflow although I'm sure someone has asked this before.
I have two numpy arrays as follows:
a = np.ones(shape = (2,10))
b = np.ones(2)
I want to multiply the first row of 10 of a by the first number in b and the second row by the second number. I can do this using lists as follows:
np.array([x*y for x,y in zip(b,a)])
I was wondering if there is a way to do this in numpy that would be a similar one liner to the list method.
I am aware I can reshape a to (1,2,10) and b to (2,1) to effectively achieve this - is this the only solution? Or is there a numpy method that can do this without manually reshaping.
This might be what you are looking for:
a*np.tile(np.expand_dims(b,axis=1),(1,10))
If you want to make use of the automatic numpy broadcasting, you need to reshape b first:
np.multiply(a, b.reshape(2,1))
The title kind of says it all. I have this (excerpt):
import numpy as np
import matplotlib.pyplot as plt
number_of_particles=1000
phi = np.arccos(1-2*np.random.uniform(0.0,1.,(number_of_particles,1)))
vc=2*pi
mux=-vc*np.sin(phi)
and I get out
[[-4.91272413]
[-5.30620302]
[-5.22400513]
[-5.5243784 ]
[-5.65050497]...]
which is correct, but I want it to be in the format
[-4.91272413 -5.30620302 -5.22400513 -5.5243784 -5.65050497....]
Feel like there should be a simple solution, but I couldn't find it.
Suppose your array is represented by the variable arr.
You can do,
l = ''
for i in arr:
l = l+i+' '
arr = [l]
Use this command:
new_mux = [i[0] for i in mux]
But I need it in an array, so then I add this
new_mux=np.array(new_mux)
and I get the desired output.
There's a method transpose in numpy's array object
mux.transpose()[0]
(I just noticed that this is a very old question, but since I have typed up this answer, and I believe it is simpler and more efficient than the existing ones, I'll post it...)
Notice that when you do
np.random.uniform(0.0,1.,(number_of_particles, 1))
you are creating a two-dimensional array with number_of_particles rows and one column. If you want a one-dimensional array throughout, you could do
np.random.uniform(0.0,1.,(number_of_particles,))
instead.
If you want to keep things 2d, but reshape mux for some reason, you can... well, reshape it:
mux_1d = mux.reshape(-1)
-1 here means "reshape it to one axis (because there’s just one number) and figure out automatically home many elements there should be along that axis (because the number is -1)."
I have a multidimensional matrix and want to set the last element to 1.(e.g. w[1,1,1,1,1]= 1) The dimension varies, so thats my problem. po[-1]=1 doesn't work here.
I'm going to assume you're using NumPy since Python itself doesn't have multidimensional arrays.
The easy way to do this is using a "flat" view of the array:
myarray.flat[-1] = 1
I have a numpy matrix which I filled with data from a *.csv-file
csv = np.genfromtxt (file,skiprows=22)
matrix = np.matrix(csv)
This is a 64x64 matrix which looks like
print matrix
[[...,...,....]
[...,...,.....]
.....
]]
Now I need to take the logarithm math.log10() of every single value and safe it into another 64x64 matrix.
How can I do this? I tried
matrix_lg = np.matrix(csv)
for i in range (0,len(matrix)):
for j in range (0,len(matrix[0])):
matrix_lg[i,j]=math.log10(matrix[i,j])
but this only edited the first array (meaning the first row) of my initial matrix.
It's my first time working with python and I start getting confused.
You can just do:
matrix_lg = numpy.log10(matrix)
And it will do it for you. It's also much faster to do it this vectorized way instead of looping over every entry in python. It will also handle domain errors more gracefully.
FWIW though, the issue with your posted code is that the len() for matrices don't work exactly the same as they do for nested lists. As suggested in the comments, you can just use matrix.shape to get the proper dims to iterate through:
matrix_lg = np.matrix(csv)
for i in range(0,matrix_lg.shape[0]):
for j in range(0,matrix_lg.shape[1]):
matrix_lg[i,j]=math.log10(matrix_lg[i,j])