Change array output to one without brackets - python

I changed a sparse dictionary into an array with (np.asarray). Then, I wrote a function that used that array to return the answer of a formula. However, I did that in a way the output includes the double brackets. Let's say the output is now:
[[7.58939191]]
but should be:
7.58939191
Can someone say how I can change this easily? Or do I have to share my function for this?

One way could be item method:
x.item(0)
See the documentation:
Copy an element of an array to a standard Python scalar and return it.

You can turn it into a numpy array, then compress the dimension:
import numpy as np
a = np.squeeze(np.asarray(a))
Then you can use a just like a number, for example:
b = a + 1

Related

I want to make a numpy array

As the title says I want to make a numpy array.
array=np.random.randint(2,size=(4,4))
First question, at this time I want to make code that size can be changeable. What should I do?
top = input("Top(k):")
Second question, I want to receive k value like this and send output as much as this value.
At this time, I wanna print the top k-row indexes from the weakest to the strongest (weakest:smaller number of ones) How to do it??:(
example like this.
input
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]]
Top(k):2
output
0,2
if Top(k):4, output is
0,2,3,1
Numpy uses static arrays (it is implemented in C), you cannot change the size of a numpy array as you would with python lists. However, you can use the numpy.ndarray constructor to create a numpy array from python list: array = numpy.ndarray(my_python_array).
For you second answer you can use the function sum() of ndarray and use it like this:
histogram = []
for i in range(len(array_2D)):
# Store the row indexes as well as number of ones
histogram.append((i, array2D[i].sum()))
# Sort regarding the number of ones
histogram.sort(key=lambda e:e[1])
for index, val in histogram[:k]:
print(index, end=" ")
Here array2D is the numpy array you got from user input. You should parse the user input to get a numpy array before executing this code.

Numpy: Find the maximum length of arrays inside another array

I have a numpy array as the following:
import numpy as np
arr = np.array([np.array([1]),np.array([1,2]),np.array([1,2,3]),np.array([1,3,4,2,4,2])])
I want a nice numpy function, which gives me the maximum length of the arrays inside my arr array.
So I need a numpy function, which return for this example 6.
This is possible with iteration, but I am looking for a nicer way, perhaps even without map()
Any function inside tensorflow or keras would also be possible to use.
We could do:
max(map(len, arr))
#6
Another simple trick is to use max() function with key argument to return the array with maximum length.
len(max(arr, key = len))
Another way would be to use the keras.preprocessing.sequence.pad_sequences() function.
It pads the sequences to the lenght of the maximum, but in my opinion it creates a high memory usage and depending on the array it might take some time. However, this would be a way without looping:
len(keras.preprocessing.sequence.pad_sequences(arr)[0])

How to get arrays that ouput result in brackets like [1][2][3] to [1 2 3]

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)."

Piecewise Operation on List of Numpy Arrays

My question is, can I make a function or variable that can perform an on operation or numpy method on each np.array element within a list in a more succinct way than what I have below (preferably by just calling one function or variable)?
Generating the list of arrays:
import numpy as np
array_list = [np.random.rand(3,3) for x in range(5)]
array_list
Current Technique of operating on each element:
My current method (as seen below) involves unpacking it and doing something to it:
[arr.std() for arr in array_list]
[arr + 2 for arr in array_list]
Goal:
My hope it to get something that could perform the operations above by simply typing:
x.std()
or
x +2
Yes - use an actual NumPy array and perform your operations over the desired axes, instead of having them stuffed in a list.
actual_array = np.array(array_list)
actual_array.std(axis=(1, 2))
# array([0.15792346, 0.25781021, 0.27554279, 0.2693581 , 0.28742179])
If you generally wanted all axes except the first, this could be something like tuple(range(1, actual_array.ndim)) instead of explicitly specifying the tuple.

Is there any way to use the "out" argument of a Numpy function when modifying an array in place?

If I want to get the dot product of two arrays, I can get a performance boost by specifying an array to store the output in instead of creating a new array (if I am performing this operation many times)
import numpy as np
a = np.array([[1.0,2.0],[3.0,4.0]])
b = np.array([[2.0,2.0],[2.0,2.0]])
out = np.empty([2,2])
np.dot(a,b, out = out)
Is there any way I can take advantage of this feature if I need to modify an array in place? For instance, if I want:
out = np.array([[3.0,3.0],[3.0,3.0]])
out *= np.dot(a,b)
Yes, you can use the out argument to modify an array (e.g. array=np.ones(10)) in-place, e.g. np.multiply(array, 3, out=array).
You can even use in-place operator syntax, e.g. array *= 2.
To confirm if the array was updated in-place, you can check the memory address array.ctypes.data before and after the modification.

Categories