In other words, since you want only the first 15K elements, you can use basic slicing for this:
In [114]: arr = np.random.randn(112943)
In [115]: truncated_arr = arr[:15000]
In [116]: truncated_arr.shape
Out[116]: (15000,)
In [117]: truncated_arr = truncated_arr[None, :]
In [118]: truncated_arr.shape
Out[118]: (1, 15000)
Answer from kmario23 on Stack OverflowIn other words, since you want only the first 15K elements, you can use basic slicing for this:
In [114]: arr = np.random.randn(112943)
In [115]: truncated_arr = arr[:15000]
In [116]: truncated_arr.shape
Out[116]: (15000,)
In [117]: truncated_arr = truncated_arr[None, :]
In [118]: truncated_arr.shape
Out[118]: (1, 15000)
You can use resize:
>>> import numpy as np
>>>
>>> a = np.arange(17)
>>>
# copy
>>> np.resize(a, (3,3))
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>>
# in-place - only use if you know what you are doing
>>> a.resize((3, 3), refcheck=False)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
Note that - I presume because the interactive shell keeps some extra references to recently evaluated things - I had to use refcheck=False for the in-place version which is dangerous. In a script or module you wouldn't have to and you shouldn't.
You can use boolean indexing:
>>> a = np.linspace(1, 10, num=10)
>>> truncatevalue = 5.5
>>> a_truncated = a[a < truncatevalue]
>>> a_truncated
array([ 1., 2., 3., 4., 5.])
Essentially, a < truncatevalue returns a boolean array indicating whether or not the element of a meets the condition. Using this boolean array to index a returns a view of a in which each element's index is True.
So for the second part of your question, all you need to do is this:
>>> b = np.array([19, 17, 15, 14, 29, 33, 28, 4, 90, 6])
>>> b_truncated = b[a < truncatevalue]
>>> b_truncated
array([19, 17, 15, 14, 29])
a_truncated = [value for value in a if value < truncateValue]
actually there is a specific method for this, 'clip':
import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array.clip(0,255) # clip(min, max)
output:
array([[100, 200],
[255, 255]], dtype=uint16)
import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array[my_array > 255] = 255
the output will be
array([[100, 200],
[255, 255]], dtype=uint16)
You could slice both arrays to the smaller one and then add them:
min_size = min(a.size, b.size)
c = a[:min_size] + b[:min_size]
print(c)
array([5, 7, 9])
EDIT
If you don't want to do it manually you could write a function:
def add_func(*args):
to_trunc = min(map(len, args))
return np.sum([arg[:to_trunc] for arg in args], axis=0)
print(add_func(a,b))
[5 7 9]
So, to begin with: what you want to do is bad form. Redefining simple operations often causes all manner of headaches. Subclassing np.array for something like this seems like a horrible idea.
With that said, it is possible to do. Here's a naive way to do it:
import numpy as np
class truncarray(np.ndarray):
def __new__( cls, array ):
obj = np.asarray(array).view(cls)
return obj
def __add__( a, b ):
s = slice(0, min(len(a),len(b)))
return np.add(a[s],b[s])
__radd__ = __add__
a = truncarray([1,2,3])
b = truncarray([4,5,6,7])
a_array = np.array([1,2,3])
b_array = np.array([4,5,6,7])
Now, let's see how much this has messed up everything:
Adding truncates, as you'd prefer:
In [17]: a+b
Out[17]: truncarray([5, 7, 9])
Adding a number no longer works:
In [18]: a_array+1
Out[18]: array([2, 3, 4])
In [19]: a+1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-fdcaab9110f2> in <module>()
----> 1 a+1
<ipython-input-2-3651dc87cb0e> in __add__(a, b)
4 return obj
5 def __add__( a, b ):
----> 6 s = slice(0, min(len(a),len(b)))
7 return np.add(a[s],b[s])
8 __radd__ = __add__
TypeError: object of type 'int' has no len()
When considering a mixture of truncarrays and arrays, addition is no longer transitive:
In [20]: a+b_array+a_array
Out[20]: truncarray([ 6, 9, 12])
In [21]: b_array+a+a_array
Out[21]: truncarray([ 6, 9, 12])
In [22]: b_array+a_array+a
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-22-bcd145daa775> in <module>()
----> 1 b_array+a_array+a
ValueError: operands could not be broadcast together with shapes (4,) (3,)
In fact, it isn't even associative(!):
In [23]: a+(b_array+a_array)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-413ce83f55c2> in <module>()
----> 1 a+(b_array+a_array)
ValueError: operands could not be broadcast together with shapes (4,) (3,)
At the very least, if you do this, you'll want to add handling for differing types. But please consider Anton's answer: it's the far safer way of doing this.
Try out this modified version of numpy.trunc().
import numpy as np
def trunc(values, decs=0):
return np.trunc(values*10**decs)/(10**decs)
Sadly, numpy.trunc function doesn't allow decimal truncation. Luckily, multiplying the argument and dividing it's result by a power of ten give the expected results.
vec = np.array([-4.79, -0.38, -0.001, 0.011, 0.4444, 2.34341232, 6.999])
trunc(vec, decs=2)
which returns:
>>> array([-4.79, -0.38, -0. , 0.01, 0.44, 2.34, 6.99])
Use numpy.round:
import numpy as np
a = np.arange(4) ** np.pi
a
=> array([ 0. , 1. , 8.82497783, 31.5442807 ])
a.round(decimals=2)
=> array([ 0. , 1. , 8.82, 31.54])