numpy array of objects

You can vectorize the class’s __init__ function: import numpy as np class Site: def __init__(self, a): self.a = a def set_a(self, new_a): self.a = new_a vSite = np.vectorize(Site) init_arry = np.arange(9).reshape((3,3)) lattice = np.empty((3,3), dtype=object) lattice[:,:] = vSite(init_arry) This may look cleaner but has no performance advantage over your looping solution. The list comprehension answers … Read more

Why is numpy.array so slow?

Numpy is optimised for large amounts of data. Give it a tiny 3 length array and, unsurprisingly, it performs poorly. Consider a separate test import timeit reps = 100 pythonTest = timeit.Timer(‘a = [0.] * 1000000’) numpyTest = timeit.Timer(‘a = numpy.zeros(1000000)’, setup=’import numpy’) uninitialised = timeit.Timer(‘a = numpy.empty(1000000)’, setup=’import numpy’) # empty simply allocates the … Read more

Difference between numpy.logical_and and &

@user1121588 answered most of this in a comment, but to answer fully… “Bitwise and” (&) behaves much the same as logical_and on boolean arrays, but it doesn’t convey the intent as well as using logical_and, and raises the possibility of getting misleading answers in non-trivial cases (packed or sparse arrays, maybe). To use logical_and on … Read more

NumPy List Comprehension Syntax

First, you should not be using NumPy arrays as lists of lists. Second, let’s forget about NumPy; your listcomp doesn’t make any sense in the first place, even for lists of lists. In the inner comprehension, for i in X is going to iterate over the rows in X. Those rows aren’t numbers, they’re lists … Read more

Find unique elements of floating point array in numpy (with comparison using a delta value)

Another possibility is to just round to the nearest desirable tolerance: np.unique(a.round(decimals=4)) where a is your original array. Edit: Just to note that my solution and @unutbu’s are nearly identical speed-wise (mine is maybe 5% faster) according to my timings, so either is a good solution. Edit #2: This is meant to address Paul’s concern. … Read more

AttributeError: ‘Series’ object has no attribute ‘as_matrix’ Why is it error?

As stated in another answer, the as_matrix method is deprecated since 0.23.0, so you should use to_numpy instead. However, I want to highlight the fact that as_matrix and to_numpy have different signatures: as_matrix takes a list of column names as one of its parameter, in case you want to limit the conversion to a subset … Read more

numpy convert categorical string arrays to an integer array

np.unique has some optional returns return_inverse gives the integer encoding, which I use very often >>> b, c = np.unique(a, return_inverse=True) >>> b array([‘a’, ‘b’, ‘c’], dtype=”|S1″) >>> c array([0, 1, 2, 0, 1, 2]) >>> c+1 array([1, 2, 3, 1, 2, 3]) it can be used to recreate the original array from uniques >>> … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)