I'm trying to build a code that checks whether a given object is an np.array() in python.
if isinstance(obj,np.array()) doesn't seem to work.
I would truly appreciate any help.
isinstance(obj, numpy.ndarray) may work
Below code seems to work. Use numpy.ndarray.
import numpy as np
l = [1,2,3,4]
l_arr = np.array(l)
if isinstance(l_arr, np.ndarray):
print("Type is np.array")
else:
print("Type is not np.array")
Output:
Type is np.array
You could compare the type of the object being passed to the checking function with 'np.ndarray' to check if the given object is indeed an np.ndarray
The sample code snippet for the same should look something like this :
if isinstance(obj,np.ndarray):
# proceed -> is an np array
else
# Not an np.ndarray
The type of what numpy.array returns is numpy.ndarray. You can determine that in the repl by calling type(numpy.array([])). Note that this trick works even for things where the raw class is not publicly accessible. It's generally better to use the direct reference, but storing the return from type(someobj) for later comparison does have its place.
Related
How do I properly create type hints if the value isn't assigned yet.
For example:
class foo():
def __init__():
data: np.ndarray = None
def load_data():
data = np.loadtxt(...)
Now I obviously get a warning, that type ndarray is expected, and not None. What is an elegant solution to this? Do I just make up some ndarray like data: np.ndarray = np.array([])? That seams just wrong to me, and I'm sure there is a better way of doing it.
I still prefer the None version, because if there is an error with reading the numpy array, I will get an error like "can't calculate ... with type None". Then I imideatly know, it didn't read the file. Whereas, if the array is just empty, I might get weird errors, I don't understand.
SOLUTION:
Thanks to the commentators, pointing this out. The solution is importing Optional from typing, and then use Optional[np.ndarray] instead of np.ndarray
Consider using data: np.ndarray = np.empty([])
Or if you know the dimension of the array, initialize it with its dimensions.
See numpy.empty for more information.
Good Luck,
Ben
I have defined my own class which takes in any matrix and is defined in such a way to convert this matrix into three numpy arrays inside a parenthesis (which I assume means it's a tuple). Furthermore, I have added a getitem method which allows output arrays to be subscript-able just like normal arrays.
My class is called MatrixConverter, and say x is some random matrix, then:
q=MatrixConverter(x)
Where q gives:
q=(array[1,2,3,4],array[5,6,7,8],array[9,10,11,12])
(Note that this is just an example, it does not produce three arrays with consecutive numbers)
Then, for example, by my getitem method, it allows for:
q[0] = array[1,2,3,4]
q[0][1] = 2
Now, I'm attempting to design a method to add en element into one of the arrays using the np.insert function such as the following:
class MatrixConverter
#some code here
def __change__(self,n,x):
self[1]=np.insert(self[1],n,x)
return self
Then, my desired output for the case where n=2 and x=70 is the following:
In:q.__change__(2,70)
Out:(array[1,2,3,4],array[5,6,70,7,8],array[9,10,11,12])
However, this gives me a TypeError: 'MatrixConverter' object does not support item assignment.
Any help/debugs? Should I perhaps use np.concentate instead?
Thank you!
Change your method to:
def __change__(self,n,x):
temp = np.insert(self[1],n,x)
self[1] = temp
return self
This will help you distinguish between a problem with the insert and a problem with the self[1] = ... setting.
I don't think the problem is with the insert call, but you need to write code that doesn't confuse you on such matters. That's a basic part of debugging.
Beyond that you haven't given us enough code to help you. For example what's the "getitem".
Expressions like array[1,2,3,4] tell me that you aren't actually copying from your code. That's not a valid Python expression, or array display.
import numpy as np
ze=np.zeros(3)
print(ze[0]) # -> 0
I am pretty new to Python (3.5.2)
I learned 'list' in python and to show the i th element in list1
print (list1[i])
but, even 'np.zeros(3)' is ndarray, a class in NumPy,
it can be used as the 'list' like above.
What is happening on that?
I am pretty new but I have worked on Java..so I hope the issues can be understood...
I guess this question is too early for one who just learned range() and not known how to define functions(methods?)..
But please let me know how to achieve the access by operator [].
Maybe it will be usefull, when I really start to Python.
If you want to implement a class that can return a value using the [] operator. Then implement the __getitem__(self, key) function in the class, see https://docs.python.org/2/reference/datamodel.html#emulating-container-types.
I have a python function that employs the numpy package. It uses numpy.sort and numpy.array functions as shown below:
def function(group):
pre_data = np.sort(np.array(
[c["data"] for c in group[1]],
dtype = np.float64
))
How can I re-write the sort and array functions using only Python in such a way that I no longer need the numpy package?
It really depends on the code after this. pre_data will be a numpy.ndarray which means that it has array methods which will be really hard to replicate without numpy. If those methods are being called later in the code, you're going to have a hard time and I'd advise you to just bite the bullet and install numpy. It's popularity is a testament to it's usefulness...
However, if you really just want to sort a list of floats and put it into a sequence-like container:
def function(group):
pre_data = sorted(float(c['data']) for c in group[1])
should do the trick.
Well, it's not strictly possible because the return type is an ndarray. If you don't mind to use a list instead, try this:
pre_data = sorted(float(c["data"]) for c in group[1])
That's not actually using any useful numpy functions anyway
def function(group):
pre_data = sorted(float(c["data"]) for c in group[1])
Is there a simple way to create an immutable NumPy array?
If one has to derive a class from ndarray to do this, what's the minimum set of methods that one has to override to achieve immutability?
You can make a numpy array unwriteable:
a = np.arange(10)
a.flags.writeable = False
a[0] = 1
# Gives: ValueError: assignment destination is read-only
Also see the discussion in this thread:
http://mail.scipy.org/pipermail/numpy-discussion/2008-December/039274.html
and the documentation:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html
I have a subclass of Array at this gist: https://gist.github.com/sfaleron/9791418d7023a9985bb803170c5d93d8
It makes a copy of its argument and marks that as read-only, so you should only be able to shoot yourself in the foot if you are very deliberate about it. My immediate need was for it to be hashable, so I could use them in sets, so that works too. It isn't a lot of code, but about 70% of the lines are for testing, so I won't post it directly.
Note that it's not a drop-in replacement; it won't accept any keyword args like a normal Array constructor. Instances will behave like Arrays, though.
Setting the flag directly didn't work for me, but using ndarray.setflags did work:
a = np.arange(10)
a.setflags(write=False)
a[0] = 1 # ValueError