text
stringlengths
29
2.66k
source
stringclasses
5 values
**numpy division with RuntimeWarning: invalid value encountered in double_scalars** **Top answer** You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero. This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero. nan is returned in this case because of the division by zero. Now to solve your problem you could: go for a library for high-precision mathematics, like mpmath. But that's less fun. as an alternative to a bigger weapon, do some math manipulation, as detailed below. go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer. Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator: exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y))) = exp(log(exp(-x)*[1+exp(-y+x)])) = exp(log(exp(-x) + log(1+exp(-y+x))) = exp(-x + log(1+exp(-y+x))) where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is -x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06 For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the
stackoverflow.com
**how to convert 2d list to 2d numpy array?** **Top answer** Just pass the list to np.array: a = np.array(a) You can also take this opportunity to set the dtype if the default is not what you desire. a = np.array(a, dtype=...)
stackoverflow.com
**Installing Numpy on 64bit Windows 7 with Python 2.7.3** **Top answer** Try the (unofficial) binaries in this site: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy You can get the newest numpy x64 with or without Intel MKL libs for Python 2.7 or Python 3.
stackoverflow.com
**What does the c underscore expression `c_` do exactly?** **Top answer** It took me a lot of time to understand but it seems I finally got it. All you have to do is add along second axis. let's take : np.c_[np.array([1,2,3]), np.array([4,5,6])] But there isn't second axis. So we mentally add one. so shape of both array becomes (3,1). So resultant shape would be (3,1+1) which is (3,2). which is the shape of result - array([[1, 4], [2, 5], [3, 6]]) Another ex.: np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] shapes: np.array([[1,2,3]]) = 1,3 np.array([[4,5,6]]) = 1,3 0 so we can think of it as [[0]] = 1,1 So result 1,3+1+1+3 = 1,8 which is the shape of result : array([[1, 2, 3, 0, 0, 4, 5, 6]])
stackoverflow.com
**pandas select from Dataframe using startswith** **Top answer** You can use the str.startswith DataFrame method to give more consistent results: In [11]: s = pd.Series(['a', 'ab', 'c', 11, np.nan]) In [12]: s Out[12]: 0 a 1 ab 2 c 3 11 4 NaN dtype: object In [13]: s.str.startswith('a', na=False) Out[13]: 0 True 1 True 2 False 3 False 4 False dtype: bool and the boolean indexing will work just fine (I prefer to use loc, but it works just the same without): In [14]: s.loc[s.str.startswith('a', na=False)] Out[14]: 0 a 1 ab dtype: object . It looks least one of your elements in the Series/column is a float, which doesn't have a startswith method hence the AttributeError, the list comprehension should raise the same error...
stackoverflow.com
**Should I use np.absolute or np.abs?** **Top answer** It's likely because there a built-in functions with the same name, abs. The same is true for np.amax, np.amin and np.round_. The aliases for the NumPy functions abs, min, max and round are only defined in the top-level package. So np.abs and np.absolute are completely identical. It doesn't matter which one you use. There are several advantages to the short names: They are shorter and they are known to Python programmers because the names are identical to the built-in Python functions. So end-users have it easier (less to type, less to remember). But there are reasons to have different names too: NumPy (or more generally 3rd party packages) sometimes need the Python functions abs, min, etc. So inside the package they define functions with a different name so you can still access the Python functions - and just in the top-level of the package you expose the "shortcuts". Note: Different names are not the only available option in that case: One could work around that with the Python module builtins to access the built-in functions if one shadowed a built-in name. It might also be the case (but that's pure speculation on my part) that they originally only included the long-named functions absolute (and so on) and only added the short aliases later. Being a large and well-used library the NumPy developers don't remove or deprecate stuff lightly. So they may just keep the long names around because it could break old code/scripts if they would remove them.
stackoverflow.com
**AttributeError: 'Tensor' object has no attribute 'numpy'** **Top answer** Since the accepted answer did not solve the problem for me so I thought it might be helpful for some people who face the problem and that already have tensorflow version >= 2.2.0 and eager execution enabled. The issue seems to be that for certain functions during the fitting model.fit() the @tf.function decorator prohibits the execution of functions like tensor.numpy() for performance reasons. The solution for me was to pass the flag run_eagerly=True to the model.compile() like this: model.compile(..., run_eagerly=True)
stackoverflow.com
**shuffle vs permute numpy** **Top answer** np.random.permutation has two differences from np.random.shuffle: if passed an array, it will return a shuffled copy of the array; np.random.shuffle shuffles the array inplace if passed an integer, it will return a shuffled range i.e. np.random.shuffle(np.arange(n)) If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle the elements randomly. The source code might help to understand this: 3280 def permutation(self, object x): ... 3307 if isinstance(x, (int, np.integer)): 3308 arr = np.arange(x) 3309 else: 3310 arr = np.array(x) 3311 self.shuffle(arr) 3312 return arr
stackoverflow.com
**What is the difference between np.mean and tf.reduce_mean?** **Top answer** The functionality of numpy.mean and tensorflow.reduce_mean are the same. They do the same thing. From the documentation, for numpy and tensorflow, you can see that. Lets look at an example, c = np.array([[3.,4], [5.,6], [6.,7]]) print(np.mean(c,1)) Mean = tf.reduce_mean(c,1) with tf.Session() as sess: result = sess.run(Mean) print(result) Output [ 3.5 5.5 6.5] [ 3.5 5.5 6.5] Here you can see that when axis(numpy) or reduction_indices(tensorflow) is 1, it computes mean across (3,4) and (5,6) and (6,7), so 1 defines across which axis the mean is computed. When it is 0, the mean is computed across(3
stackoverflow.com
**Inverting a numpy boolean array using ~** **Top answer** short answer: YES Ref: http://docs.scipy.org/doc/numpy/reference/generated/numpy.invert.html Notice: Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~. and bitwise_not is an alias for invert: >> np.bitwise_not is np.invert >> True
stackoverflow.com
**Python Pandas - Changing some column types to categories** **Top answer** Sometimes, you just have to use a for-loop: for col in ['parks', 'playgrounds', 'sports', 'roading']: public[col] = public[col].astype('category')
stackoverflow.com
**Pandas: convert dtype 'object' to int** **Top answer** Documenting the answer that worked for me based on the comment by @piRSquared. I needed to convert to a string first, then an integer. >>> df['purchase'].astype(str).astype(int)
stackoverflow.com
**Comparing numpy arrays containing NaN** **Top answer** For versions of numpy prior to 1.19, this is probably the best approach in situations that don't specifically involve unit tests: >>> ((a == b) | (numpy.isnan(a) & numpy.isnan(b))).all() True However, modern versions provide the array_equal function with a new keyword argument, equal_nan, which fits the bill exactly. This was first pointed out by flyingdutchman; see his answer below for details.
stackoverflow.com
**Differences between numpy.random.rand vs numpy.random.randn in Python** **Top answer** First, as you see from the documentation numpy.random.randn generates samples from the normal distribution, while numpy.random.rand from a uniform distribution (in the range [0,1)). Second, why did the uniform distribution not work? The main reason is the activation function, especially in your case where you use the sigmoid function. The plot of the sigmoid looks like the following: So you can see that if your input is away from 0, the slope of the function decreases quite fast and as a result you get a tiny gradient and tiny weight update. And if you have many layers - those gradients get multiplied many times in the back pass, so even "proper" gradients after multiplications become small and stop making any influence. So if you have a lot of weights which bring your input to those regions you network is hardly trainable. That's why it is a usual practice to initialize network variables around zero value. This is done to ensure that you get reasonable gradients (close to 1) to train your net. However, uniform distribution is not something completely undesirable, you just need to make the range smaller and closer to zero. As one of good practices is using Xavier initialization. In this approach you can initialize your weights with: Normal distribution. Where mean is 0 and var = sqrt(2. / (in + out)), where in - is the number of inputs to the neurons and out - number of outputs. Uniform distribution in range [-sqrt(6. / (in + out)), +sqrt(6. / (in + out))]
stackoverflow.com
**How to have logarithmic bins in a Python histogram** **Top answer** use logspace() to create a geometric sequence, and pass it to bins parameter. And set the scale of xaxis to log scale. import pylab as pl import numpy as np data = np.random.normal(size=10000) pl.hist(data, bins=np.logspace(np.log10(0.1),np.log10(1.0), 50)) pl.gca().set_xscale("log") pl.show()
stackoverflow.com
**TypeError: ufunc &#39;isnan&#39; not supported for the input types, and the inputs could not be safely coerced** **Top answer** Posting as it might help future users. As correctly pointed out by others, np.isnan won't work for object or string dtypes. If you're using pandas, as mentioned here you can directly use pd.isnull, which should work in your case. import pandas as pd import numpy as np var1 = '' var2 = np.nan >>> type(var1) <class 'str'> >>> type(var2) <class 'float'> >>> pd.isnull(var1) False >>> pd.isnull(var2) True
stackoverflow.com
**Share Large, Read-Only Numpy Array Between Multiprocessing Processes** **Top answer** If you are on Linux (or any POSIX-compliant system), you can define this array as a global variable. multiprocessing is using fork() on Linux when it starts a new child process. A newly spawned child process automatically shares the memory with its parent as long as it does not change it (copy-on-write mechanism). Since you are saying "I don't need any kind of locks, since the array (actually a matrix) will be read-only" taking advantage of this behavior would be a very simple and yet extremely efficient approach: all child processes will access the same data in physical memory when reading this large numpy array. Don't hand your array to the Process() constructor, this will instruct multiprocessing to pickle the data to the child, which would be extremely inefficient or impossi
stackoverflow.com
**How to make scipy.interpolate give an extrapolated result beyond the input range?** **Top answer** As of SciPy version 0.17.0, there is a new option for scipy.interpolate.interp1d that allows extrapolation. Simply set fill_value='extrapolate' in the call. Modifying your code in this way gives: import numpy as np from scipy import interpolate x = np.arange(0,10) y = np.exp(-x/3.0) f = interpolate.interp1d(x, y, fill_value='extrapolate') print f(9) print f(11) and the output is: 0.0497870683679 0.010394302658 Unfortunately, as of 2024, there is a warning in the docs for interp1d: This class is considered legacy and will no longer receive updates. This could also mean it will be removed in future SciPy versions.
stackoverflow.com
**How to get stable results with TensorFlow, setting random seed** **Top answer** Setting the current TensorFlow random seed affects the current default graph only. Since you are creating a new graph for your training and setting it as default (with g.as_default():), you must set the random seed within the scope of that with block. For example, your loop should look like the following: for i in range(3): g = tf.Graph() with g.as_default(): tf.set_random_seed(1) accuracy_result, average_error = network.train_network( parameters, inputHeight, inputWidth, inputChannels, outputClasses) Note that this will use the same random seed for each iteration of the outer for loop. If you want to use a different—but still deterministic—seed in each iteration, you can use tf.set_random_seed(i + 1).
stackoverflow.com
**How to implement the ReLU function in Numpy** **Top answer** There are a couple of ways. >>> x = np.random.random((3, 2)) - 0.5 >>> x array([[-0.00590765, 0.18932873], [-0.32396051, 0.25586596], [ 0.22358098, 0.02217555]]) >>> np.maximum(x, 0) array([[ 0. , 0.18932873], [ 0. , 0.25586596], [ 0.22358098, 0.02217555]]) >>> x * (x > 0) array([[-0. , 0.18932873], [-0. , 0.25586596], [ 0.22358098, 0.02217555]]) >>> (abs(x) + x) / 2 array([[ 0. , 0.18932873], [ 0. , 0.25586596], [ 0.22358098, 0.02217555]]) If timing the results with the following code: import numpy as np x = np.random.random((5000, 5000)) - 0.5 print("max method:") %timeit -n10 np.maximum(x, 0) print("multiplication method:") %timeit -n10 x * (x > 0) print("abs method:") %timeit -n10 (abs(x) + x) / 2 We get: max method: 10 loops, best of 3: 239 ms per loop multiplication method: 10 loops, best of 3: 145 ms per loop abs method: 10 loops, best of 3: 288 ms per loop So the multiplication seems to be the fastest.
stackoverflow.com
**&quot;isnotnan&quot; functionality in numpy, can this be more pythonic?** **Top answer** a = a[~np.isnan(a)]
stackoverflow.com
**How to load a list of numpy arrays to pytorch dataset loader?** **Top answer** I think what DataLoader actually requires is an input that subclasses Dataset. You can either write your own dataset class that subclasses Datasetor use TensorDataset as I have done below: import torch import numpy as np from torch.utils.data import TensorDataset, DataLoader my_x = [np.array([[1.0,2],[3,4]]),np.array([[5.,6],[7,8]])] # a list of numpy arrays my_y = [np.array([4.]), np.array([2.])] # another list of numpy arrays (targets) tensor_x = torch.Tensor(my_x) # transform to torch tensor tensor_y = torch.Tensor(my_y) my_dataset = TensorDataset(tensor_x,tensor_y) # create your datset my_dataloader = DataLoader(my_dataset) # create your dataloader Works for me.
stackoverflow.com
**Could not install packages due to a &quot;Environment error :[error 13]: permission denied : &#39;usr/local/bin/f2py&#39;&quot;** **Top answer** This worked for me. pip3 install --user package-name # for Python3 pip install --user package-name # for Python2 The --user flag tells Python to install in the user home directory. By default it will go to system locations. credit
stackoverflow.com
**Calculate mean across dimension in a 2D array** **Top answer** a.mean() takes an axis argument: In [1]: import numpy as np In [2]: a = np.array([[40, 10], [50, 11]]) In [3]: a.mean(axis=1) # to take the mean of each row Out[3]: array([ 25. , 30.5]) In [4]: a.mean(axis=0) # to take the mean of each col Out[4]: array([ 45. , 10.5]) Or, as a standalone function: In [5]: np.mean(a, axis=1) Out[5]: array([ 25. , 30.5]) The reason your slicing wasn't working is because this is the syntax for slicing: In [6]: a[:,0].mean() # first column Out[6]: 45.0 In [7]: a[:,1].mean() # second column Out[7]: 10.5
stackoverflow.com
**Fastest way to grow a numpy numeric array** **Top answer** I tried a few different things, with timing. import numpy as np The method you mention as slow: (32.094 seconds) class A: def __init__(self): self.data = np.array([]) def update(self, row): self.data = np.append(self.data, row) def finalize(self): return np.reshape(self.data, newshape=(self.data.shape[0]/5, 5)) Regular ol Python list: (0.308 seconds) class B: def __init__(self): self.data = [] def update(self, row): for r in row: self.data.append(r) def finalize(self): return np.reshape(self.data, newshape=(len(self.data)/5, 5)) Trying to implement an arraylist in numpy: (0.362 seconds) class C: def __init__(self): self.data = np.zeros((100,)) self.capacity = 100 self.size = 0 def update(self, row): for r in row: self.add(r) def add(self, x): if self.size == self.capacity: self.capacity *= 4 newdata = np.zeros((self.capacity,)) newdata[:self.size] = self.data self.data = newdata self.data[self.size] = x self.size += 1 def finalize(self): data = self.data[:self.size] return np.reshape(data, newshape=(len(data)/5, 5)) And this is how I timed it: x = C() for i in xrange(100000): x.update([i]) So it looks like regular old Python lists are pretty good ;)
stackoverflow.com
**How can I retrieve the current seed of NumPy&#39;s random number generator?** **Top answer** The short answer is that you simply can't (at least not in general). The Mersenne Twister RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique integer seed. You can get and set the internal state of the RNG directly using np.random.get_state and np.random.set_state. The output of get_state is a tuple whose second element is a (624,) array of 32 bit integers. This array has more than enough bits to represent every possible internal state of the RNG (2624 * 32 > 219937-1). The tuple returned by get_state can be used much like a seed in order to create reproducible sequences of random numbers. For example: import numpy as np # randomly initialize the RNG from some platform-dependent source of entropy np.random.seed(None) # get the initial state of the RNG st0 = np.random.get_state() # draw some random numbers print(np.random.randint(0, 100, 10)) # [ 8 76 76 33 77 26 3 1 68 21] # set the state back to what it was originally np.random.set_state(st0) # draw again print(np.random.randint(0, 100, 10)) # [ 8 76 76 33 77 26 3 1 68 21]
stackoverflow.com
**Optimize finding index of nearest point in 2d arrays** **Top answer** Here is a scipy.spatial.KDTree example In [1]: from scipy import spatial In [2]: import numpy as np In [3]: A = np.random.random((10,2))*100 In [4]: A Out[4]: array([[ 68.83402637, 38.07632221], [ 76.84704074, 24.9395109 ], [ 16.26715795, 98.52763827], [ 70.99411985, 67.31740151], [ 71.72452181, 24.13516764], [ 17.22707611, 20.65425362], [ 43.85122458, 21.50624882], [ 76.71987125, 44.95031274], [ 63.77341073, 78.87417774], [ 8.45828909, 30.18426696]]) In [5]: pt = [6, 30] # <-- the point to find In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point Out[6]: array([ 8.45828909, 30.18426696]) #how it works! In [7]: distance,index = spatial.KDTree(A).query(pt) In [8]: distance # <-- The distances to the nearest neighbors Out[8]: 2.4651855048258393 In [9]: index # <-- The locations of the neighbors Out[9]: 9 #then In [10]: A[index] Out[10]: array([ 8.45828909, 30.18426696])
stackoverflow.com
**How does python numpy.where() work?** **Top answer** How do they achieve internally that you are able to pass something like x > 5 into a method? The short answer is that they don't. Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true). E.g. x = np.arange(9).reshape(3,3) print x > 5 yields: array([[False, False, False], [False, False, False], [ True, True, True]], dtype=bool) This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value. Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case. Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.
stackoverflow.com
**Why does numpy std() give a different result to matlab std()?** **Top answer** The NumPy function np.std takes an optional parameter ddof: "Delta Degrees of Freedom". By default, this is 0. Set it to 1 to get the MATLAB result: >>> np.std([1,3,4,6], ddof=1) 2.0816659994661326 To add a little more context, in the calculation of the variance (of which the standard deviation is the square root) we typically divide by the number of values we have. But if we select a random sample of N elements from a larger distribution and calculate the variance, division by N can lead to an underestimate of the actual variance. To fix this, we can lower the number we divide by (the degrees of freedom) to a number less than N (usually N-1). The ddof parameter allows us change the divisor by the amount we specify. Unless told otherwise, NumPy will calculate the biased estimator for the variance (ddof=0, dividing by N). This is what you want if you are working with the entire distribution (and not a subset of values which have been randomly picked from a larger distribution). If the ddof parameter is given, NumPy divides by N - ddof instead. The default behaviour of MATLAB's std is to correct the bias for sample variance by dividing by N-1. This gets rid of some of (but probably not all of) of the bias in the standard deviation. This is likely to be what you want if you're using the function on a random sample of a larger distribution. The nice answer by @hbaderts gives further mathematical details.
stackoverflow.com
**IndexError: too many indices for array** **Top answer** I think the problem is given in the error message, although it is not very easy to spot: IndexError: too many indices for array xs = data[:, col["l1" ]] 'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None). This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function. I highly recommend in your for loop inserting: print(data) This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.
stackoverflow.com
**How do you find the IQR in Numpy?** **Top answer** np.percentile takes multiple percentile arguments, and you are slightly better off doing: q75, q25 = np.percentile(x, [75 ,25]) iqr = q75 - q25 or iqr = np.subtract(*np.percentile(x, [75, 25])) than making two calls to percentile: In [8]: x = np.random.rand(1e6) In [9]: %timeit q75, q25 = np.percentile(x, [75 ,25]); iqr = q75 - q25 10 loops, best of 3: 24.2 ms per loop In [10]: %timeit iqr = np.subtract(*np.percentile(x, [75, 25])) 10 loops, best of 3: 24.2 ms per loop In [11]: %timeit iqr = np.percentile(x, 75) - np.percentile(x, 25) 10 loops, best of 3: 33.7 ms per loop
stackoverflow.com
**Immutable numpy array?** **Top answer** 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
stackoverflow.com
**Find out if a matrix is positive definite with NumPy** **Top answer** You can also check if all the eigenvalues of matrix are positive. If so, the matrix is positive definite: import numpy as np def is_pos_def(x): return np.all(np.linalg.eigvals(x) > 0)
stackoverflow.com
**Why does corrcoef return a matrix?** **Top answer** It allows you to compute correlation coefficients of >2 data sets, e.g. >>> from numpy import * >>> a = array([1,2,3,4,6,7,8,9]) >>> b = array([2,4,6,8,10,12,13,15]) >>> c = array([-1,-2,-2,-3,-4,-6,-7,-8]) >>> corrcoef([a,b,c]) array([[ 1. , 0.99535001, -0.9805214 ], [ 0.99535001, 1. , -0.97172394], [-0.9805214 , -0.97172394, 1. ]]) Here we can get the correlation coefficient of a,b (0.995), a,c (-0.981) and b,c (-0.972) at once. The two-data-set case is just a special case of N-data-set class. And probably it's better to keep the same return type. Since the "one value" can be obtained simply with >>> corrcoef(a,b)[1,0] 0.99535001355530017 there's no big reason to create the special case.
stackoverflow.com
**Python: Concatenate (or clone) a numpy array N times** **Top answer** You are close, you want to use np.tile, but like this: a = np.array([0,1,2]) np.tile(a,(3,1)) Result: array([[0, 1, 2], [0, 1, 2], [0, 1, 2]]) If you call np.tile(a,3) you will get concatenate behavior like you were seeing array([0, 1, 2, 0, 1, 2, 0, 1, 2]) http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html
stackoverflow.com
**Using a pre-trained word embedding (word2vec or Glove) in TensorFlow** **Top answer** There are a few ways that you can use a pre-trained embedding in TensorFlow. Let's say that you have the embedding in a NumPy array called embedding, with vocab_size rows and embedding_dim columns and you want to create a tensor W that can be used in a call to tf.nn.embedding_lookup(). Simply create W as a tf.constant() that takes embedding as its value: W = tf.constant(embedding, name="W") This is the easiest approach, but it is not memory efficient because the value of a tf.constant() is stored multiple times in memory. Since embedding can be very large, you should only use this approach for toy examples. Create W as a tf.Variable and initialize it from the NumPy array via a tf.placeholder(): W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]), trainable=False, name="W") emb
stackoverflow.com
**Most efficient property to hash for numpy array** **Top answer** You can simply hash the underlying buffer, if you make it read-only: >>> a = random.randint(10, 100, 100000) >>> a.flags.writeable = False >>> %timeit hash(a.data) 100 loops, best of 3: 2.01 ms per loop >>> %timeit hash(a.tostring()) 100 loops, best of 3: 2.28 ms per loop For very large arrays, hash(str(a)) is a lot faster, but then it only takes a small part of the array into account. >>> %timeit hash(str(a)) 10000 loops, best of 3: 55.5 us per loop >>> str(a) '[63 30 33 ..., 96 25 60]'
stackoverflow.com
**Very large matrices using Python and NumPy** **Top answer** PyTables and NumPy are the way to go. PyTables will store the data on disk in HDF format, with optional compression. My datasets often get 10x compression, which is handy when dealing with tens or hundreds of millions of rows. It's also very fast; my 5 year old laptop can crunch through data doing SQL-like GROUP BY aggregation at 1,000,000 rows/second. Not bad for a Python-based solution! Accessing the data as a NumPy recarray again is as simple as: data = table[row_from:row_to] The HDF library takes care of reading in the relevant chunks of data and converting to NumPy.
stackoverflow.com
**How to copy data from a numpy array to another** **Top answer** I believe a = numpy.empty_like(b) a[:] = b will copy the values quickly. As Funsi mentions, recent versions of numpy also have the copyto function.
stackoverflow.com
**How to make numpy.argmax return all occurrences of the maximum?** **Top answer** As documentation of np.argmax says: "In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.", so you will need another strategy. One option you have is using np.argwhere in combination with np.amax: >>> import numpy as np >>> listy = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6] >>> winner = np.argwhere(listy == np.amax(listy)) >>> print(winner) [[0] [3] [5]] >>> print(winner.flatten().tolist()) # if you want it as a list [0, 3, 5]
stackoverflow.com
**How to one-hot-encode from a pandas column containing a list?** **Top answer** We can also use sklearn.preprocessing.MultiLabelBinarizer: Often we want to use sparse DataFrame for the real world data in order to save a lot of RAM. Sparse solution (for Pandas v0.25.0+) from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer(sparse_output=True) df = df.join( pd.DataFrame.sparse.from_spmatrix( mlb.fit_transform(df.pop('Col3')), index=df.index, columns=mlb.classes_)) result: In [38]: df Out[38]: Col1 Col2 Apple Banana Grape Orange 0 C 33.0 1 1 0 1 1 A 2.5 1 0 1 0 2 B 42.0 0 1 0 0 In [39]: df.dtypes Out[39]: Col1 object Col2 float64 Apple Sparse[int32, 0] Banana Sparse[int32, 0] Grape Sparse[int32, 0] Orange Sparse[int32, 0] dtype: object In [40]: df.memory_usage() Out[40]: Index 128 Col1 24 Col2 24 Apple 16 # <--- NOTE! Banana 16 # <--- NOTE! Grape 8 # <--- NOTE! Orange 8 # <--- NOTE! dtype: int64 Dense solution mlb = MultiLabelBinarizer() df = df.join(pd.DataFrame(mlb.fit_transform(df.pop('Col3')), columns=mlb.classes_, index=df.index)) Result: In [77]: df Out[77]: Col1 Col2 Apple Banana Grape Orange 0 C 33.0 1 1 0 1 1 A 2.5 1 0 1 0 2 B 42.0 0 1 0 0
stackoverflow.com
**How to apply numpy.linalg.norm to each row of a matrix?** **Top answer** For numpy 1.9+ Note that, as perimosocordiae shows, as of NumPy version 1.9, np.linalg.norm(x, axis=1) is the fastest way to compute the L2-norm. For numpy < 1.9 If you are computing an L2-norm, you could compute it directly (using the axis=-1 argument to sum along rows): np.sum(np.abs(x)**2,axis=-1)**(1./2) Lp-norms can be computed similarly of course. It is considerably faster than np.apply_along_axis, though perhaps not as convenient: In [48]: %timeit np.apply_along_axis(np.linalg.norm, 1, x) 1000 loops, best of 3: 208 us per loop In [49]: %timeit np.sum(np.abs(x)**2,axis=-1)**(1./2) 100000 loops, best of 3: 18.3 us per loop Other ord forms of norm can be computed directly too (with similar speedups): In [55]: %timeit np.apply_along_axis(lambda row:np.linalg.norm(row,ord=1), 1, x) 1000 loops, best of 3: 203 us per loop In [54]: %timeit np.sum(abs(x), axis=-1) 100000 loops, best of 3: 10.9 us per loop
stackoverflow.com
**How to convert list of model objects to pandas dataframe?** **Top answer** A much cleaner way to to this is to define a to_dict method on your class and then use pandas.DataFrame.from_records class Signal(object): def __init__(self, x, y): self.x = x self.y = y def to_dict(self): return { 'x': self.x, 'y': self.y, } e.g. In [87]: signals = [Signal(3, 9), Signal(4, 16)] In [88]: pandas.DataFrame.from_records([s.to_dict() for s in signals]) Out[88]: x y 0 3 9 1 4 16
stackoverflow.com
**What is the most efficient way to check if a value exists in a NumPy array?** **Top answer** How about if value in my_array[:, col_num]: do_whatever Edit: I think __contains__ is implemented in such a way that this is the same as @detly's version
stackoverflow.com
**Pandas Split Dataframe into two Dataframes at a specific column** **Top answer** iloc df1 = datasX.iloc[:, :72] df2 = datasX.iloc[:, 72:] (iloc docs)
stackoverflow.com
**Get the position of the largest value in a multi-dimensional NumPy array** **Top answer** The argmax() method should help. Update (After reading comment) I believe the argmax() method would work for multi dimensional arrays as well. The linked documentation gives an example of this: >>> a = array([[10,50,30],[60,20,40]]) >>> maxindex = a.argmax() >>> maxindex 3 Update 2 (Thanks to KennyTM's comment) You can use unravel_index(a.argmax(), a.shape) to get the index as a tuple: >>> from numpy import unravel_index >>> unravel_index(a.argmax(), a.shape) (1, 0)
stackoverflow.com
**How to solve a pair of nonlinear equations using Python?** **Top answer** for numerical solution, you can use fsolve: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve from scipy.optimize import fsolve import math def equations(p): x, y = p return (x+y**2-4, math.exp(x) + x*y - 3) x, y = fsolve(equations, (1, 1)) print equations((x, y))
stackoverflow.com
**How to calculate 1st and 3rd quartiles?** **Top answer** By using pandas: df.time_diff.quantile([0.25,0.5,0.75]) Out[793]: 0.25 0.483333 0.50 0.500000 0.75 0.516667 Name: time_diff, dtype: float64
stackoverflow.com
**Save / load scipy sparse csr_matrix in portable data format** **Top answer** edit: scipy 0.19 now has scipy.sparse.save_npz and scipy.sparse.load_npz. from scipy import sparse sparse.save_npz("yourmatrix.npz", your_matrix) your_matrix_back = sparse.load_npz("yourmatrix.npz") For both functions, the file argument may also be a file-like object (i.e. the result of open) instead of a filename. Got an answer from the Scipy user group: A csr_matrix has 3 data attributes that matter: .data, .indices, and .indptr. All are simple ndarrays, so numpy.save will work on them. Save the three arrays with numpy.save or numpy.savez, load them back with numpy.load, and then recreate the sparse matrix object with: new_csr = csr_matrix((data, indices, indptr), shape=(M, N)) So for example: def save_sparse_csr(filename, array): np.savez(filename, data=array.data, indices=array.indices, indptr=array.indptr, shape=array.shape) def load_sparse_csr(filename): loader = np.load(filename) return csr_matrix((loader['data'], loader['indices'], loader['indptr']), shape=loader['shape'])
stackoverflow.com
**Get year, month or day from numpy datetime64** **Top answer** I find the following tricks give between 2x and 4x speed increase versus the pandas method described in this answer (i.e. pd.DatetimeIndex(dates).year etc.). The speed of [dt.year for dt in dates.astype(object)] I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.) dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01')) years = dates.astype('datetime64[Y]').astype(int) + 1970 months = dates.astype('datetime64[M]').astype(int) % 12 + 1 days = dates - dates.astype('datetime64[M]') + 1
stackoverflow.com
**Understanding NumPy&#39;s Convolve** **Top answer** Convolution is a mathematical operator primarily used in signal processing. Numpy simply uses this signal processing nomenclature to define it, hence the "signal" references. An array in numpy is a signal. The convolution of two signals is defined as the integral of the first signal, reversed, sweeping over ("convolved onto") the second signal and multiplied (with the scalar product) at each position of overlapping vectors. The first signal is often called the kernel, especially when it is a 2-D matrix in image processing or neural networks, and the reversal becomes a mirroring in 2-D (NOT transpose). It can more clearly be understood using the animations on wikipedia. Convolutions have multiple definitions depending on the context. Some start the convolution when the overlap begins while others start when the overlap is only partial. In the case of numpy's "valid" mode, the overlap
stackoverflow.com
**Get index of a row of a pandas dataframe as an integer** **Top answer** The easier is add [0] - select first value of list with one element: dfb = df[df['A']==5].index.values.astype(int)[0] dfbb = df[df['A']==8].index.values.astype(int)[0] dfb = int(df[df['A']==5].index[0]) dfbb = int(df[df['A']==8].index[0]) But if possible some values not match, error is raised, because first value not exist. Solution is use next with iter for get default parameetr if values not matched: dfb = next(iter(df[df['A']==5].index), 'no match') print (dfb) 4 dfb = next(iter(df[df['A']==50].index), 'no match') print (dfb) no match Then it seems need substract 1: print (df.loc[dfb:dfbb-1,'B']) 4 0.894525 5 0.978174 6 0.859449 Name: B, dtype: float64 Another solution with boolean indexing or query: print (df[(df['A'] >= 5) & (df['A'] < 8)]) A B 4 5 0.894525 5 6 0.978174 6 7 0.859449 print (df.loc[(df['A'] >= 5) & (df['A'] < 8), 'B']) 4 0.894525 5 0.978174 6 0.859449 Name: B, dtype: float64 print (df.query('A >= 5 and A < 8')) A B 4 5 0.894525 5 6 0.978174 6 7 0.859449
stackoverflow.com
**3-dimensional array in numpy** **Top answer** You have a truncated array representation. Let's look at a full example: >>> a = np.zeros((2, 3, 4)) >>> a array([[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]]) Arrays in NumPy are printed as the word array followed by structure, similar to embedded Python lists. Let's create a similar list: >>> l = [[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]] >>> l [[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]] The first level of this compound list l has exactly 2 elements, just as the first dimension of the array a (# of r
stackoverflow.com
**Numpy: Checking if a value is NaT** **Top answer** NumPy has an isnat function as of version 1.13.0: import numpy as np np.isnat(np.datetime64("NaT")) pandas can check for NaT with pandas.isnull: >>> import numpy as np >>> import pandas as pd >>> pd.isnull(np.datetime64('NaT')) True If you don't want to use pandas you can also define your own function (parts are taken from the pandas source): nat_as_integer = np.datetime64('NAT').view('i8') def isnat(your_datetime): dtype_string = str(your_datetime.dtype) if 'datetime64' in dtype_string or 'timedelta64' in dtype_string: return your_datetime.view('i8') == nat_as_integer return False # it can't be a NaT if it's not a dateime This correctly identifies NaT values: >>> isnat(np.datetime64('NAT')) True >>> isnat(np.timedelta64('NAT')) True And realizes if it's not a datetime or timedelta: >>> isnat(np.timedelta64('NAT').view('i8')) False In the future there might be an isnat-function in the numpy code, at least they have a (currently open) pull request about it: Link to the PR (NumPy github)
stackoverflow.com
**How to apply piecewise linear fit in Python?** **Top answer** You can use numpy.piecewise() to create the piecewise function and then use curve_fit(), Here is the code from scipy import optimize import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float) y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03]) def piecewise_linear(x, x0, y0, k1, k2): return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) p , e = optimize.curve_fit(piecewise_linear, x, y) xd = np.linspace(0, 15, 100) plt.plot(x, y, "o") plt.plot(xd, piecewise_linear(xd, *p)) the output: For an N parts fitting, please reference segments_fit.ipynb
stackoverflow.com
**What&#39;s the fastest way in Python to calculate cosine similarity given sparse matrix data?** **Top answer** You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output: from sklearn.metrics.pairwise import cosine_similarity from scipy import sparse A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]]) A_sparse = sparse.csr_matrix(A) similarities = cosine_similarity(A_sparse) print('pairwise dense output:\n {}\n'.format(similarities)) #also can output sparse matrices similarities_sparse = cosine_similarity(A_sparse,dense_output=False) print('pairwise sparse output:\n {}\n'.format(similarities_sparse)) Results: pairwise dense output: [[ 1. 0.40824829 0.40824829] [ 0.40824829 1. 0.33333333] [ 0.40824829 0.33333333 1. ]] pairwise sparse output: (0, 1) 0.408248290464 (0, 2) 0.408248290464 (0, 0) 1.0 (1, 0) 0.408248290464 (1, 2) 0.333333333333 (1, 1) 1.0 (2, 1) 0.333333333333 (2, 0) 0.408248290464 (2, 2) 1.0 If you want column-wise cosine similarities simply transpose your input matrix beforehand: A_sparse.transpose()
stackoverflow.com
**Averaging over every n elements of a numpy array** **Top answer** If your array arr has a length divisible by 3: np.mean(arr.reshape(-1, 3), axis=1) Reshaping to a higher dimensional array and then performing some form of reduce operation on one of the additional dimensions is a staple of numpy programming.
stackoverflow.com
**Determining duplicate values in an array** **Top answer** As of numpy version 1.9.0, np.unique has an argument return_counts which greatly simplifies your task: u, c = np.unique(a, return_counts=True) dup = u[c > 1] This is similar to using Counter, except you get a pair of arrays instead of a mapping. I'd be curious to see how they perform relative to each other. It's probably worth mentioning that even though np.unique is quite fast in practice due to its numpyness, it has worse algorithmic complexity than the Counter solution. np.unique is sort-based, so runs asymptotically in O(n log n) time. Counter is hash-based, so has O(n) complexity. This will not matter much for anything but the largest datasets.
stackoverflow.com
**How to find the groups of consecutive elements in a NumPy array** **Top answer** def consecutive(data, stepsize=1): return np.split(data, np.where(np.diff(data) != stepsize)[0]+1) a = np.array([0, 47, 48, 49, 50, 97, 98, 99]) consecutive(a) yields [array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]
stackoverflow.com
**Convert timedelta64[ns] column to seconds in Python Pandas DataFrame** **Top answer** Use the Series dt accessor to get access to the methods and attributes of a datetime (timedelta) series. >>> s 0 -1 days +23:45:14.304000 1 -1 days +23:46:57.132000 2 -1 days +23:49:25.913000 3 -1 days +23:59:48.913000 4 00:00:00.820000 dtype: timedelta64[ns] >>> >>> s.dt.total_seconds() 0 -885.696 1 -782.868 2 -634.087 3 -11.087 4 0.820 dtype: float64 There are other Pandas Series Accessors for String, Categorical, and Sparse data types.
stackoverflow.com
**Why are NumPy arrays so fast?** **Top answer** Numpy arrays are densely packed arrays of homogeneous type. Python lists, by contrast, are arrays of pointers to objects, even when all of them are of the same type. So, you get the benefits of locality of reference. Also, many Numpy operations are implemented in C, avoiding the general cost of loops in Python, pointer indirection and per-element dynamic type checking. The speed boost depends on which operations you're performing, but a few orders of magnitude isn't uncommon in number crunching programs.
stackoverflow.com
**Python RuntimeWarning: overflow encountered in long scalars** **Top answer** Here's an example which issues the same warning: import numpy as np np.seterr(all='warn') A = np.array([10]) a=A[-1] a**a yields RuntimeWarning: overflow encountered in long_scalars In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32. Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy >>> np.multiply.reduce(np.arange(21)+1) -1195114496 while on 64-bit NumPy: >>> np.multiply.reduce(np.arange(21)+1) -4249290049419214848 Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals In [47]: import math In [48]: math.factorial(21) Out[50]: 51090942171709440000L According to numpy developer, Robert Kern, Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays. So the burden is on you to choose appropriate dtypes so that no operation overflows.
stackoverflow.com
**Why are 0d arrays in Numpy not considered scalar?** **Top answer** One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual. The curious situation with Numpy scalar-types was bore out of the fact that there is no graceful and consistent way to degrade the 1x1 matrix to scalar types. Even though mathematically they are the same thing, they are handled by very different code. If you've been doing any amount of scientific code, ultimately you'd want things like max(a) to work on matrices of all sizes, even scalars. Mathematically, this is a perfectly sensible thing to expect. However for programmers this means that whatever presents scalars in Numpy should have the .shape and .ndim attirbute, so at least the ufuncs don't have to do explicit type checking on its input for the 21 possible scalar types in Numpy. On the other hand, they should also work with existing Python libraries that does do explicit type-checks on scalar type. This is a dilemma, since a Numpy ndarray have to individually change its type when they've been reduced to a scalar, and there is no way of knowing whether that has occurred without it having do checks on all access. Actually going that route would probably make bit ridiculously slow to work with by scalar type standards. The Numpy developer's sol
stackoverflow.com
**Python pickle protocol choice?** **Top answer** Use the latest protocol that supports the lowest Python version you want to support reading the data. Newer protocol versions support new language features and include optimisations. From the pickle module data format documentation: There are currently 6 different protocols which can be used for pickling. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python. Protocol version 1 is an old binary format which is also compatible with earlier versions of Python. Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2. Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This was the default protocol in Python 3.0–3.7. Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. It is the default protocol starting with Python 3.8. Refer to PEP 3154 for information about improvements brought by protocol 4. Protocol version 5 was added in Python 3.8. It adds
stackoverflow.com
**How do you Unit Test Python DataFrames** **Top answer** While Pandas' test functions are primarily used for internal testing, NumPy includes a very useful set of testing functions that are documented here: NumPy Test Support. These functions compare NumPy arrays, but you can get the array that underlies a Pandas DataFrame using the values property. You can define a simple DataFrame and compare what your function returns to what you expect. One technique you can use is to define one set of test data for a number of functions. That way, you can use Pytest Fixtures to define that DataFrame once, and use it in multiple tests. In terms of resources, I found this article on Testing with NumPy and Pandas to be very useful. I also did a short presentation about data analysis testing at PyCon Canada 2016: Automate Your Data Analysis Testing.
stackoverflow.com
**What is an intuitive explanation of np.unravel_index?** **Top answer** Computer memory is addressed linearly. Each memory cell corresponds to a number. A block of memory can be addressed in terms of a base, which is the memory address of its first element, and the item index. For example, assuming the base address is 10,000: item index 0 1 2 3 memory address 10,000 10,001 10,002 10,003 To store multi-dimensional blocks, their geometry must somehow be made to fit into linear memory. In C and NumPy, this is done row-by-row. A 2D example would be: | 0 1 2 3 --+------------------------
stackoverflow.com
**ImportError: cannot import name NUMPY_MKL** **Top answer** If you look at the line which is causing the error, you'll see this: from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl This line comment states the dependency as numpy+mkl (numpy with Intel Math Kernel Library). This means that you've installed the numpy by pip, but the scipy was installed by precompiled archive, which expects numpy+mkl. This problem can be easy solved by installation for numpy+mkl from whl file from here.
stackoverflow.com
**Binary random array with a specific proportion of ones?** **Top answer** Yet another approach, using np.random.choice: >>> np.random.choice([0, 1], size=(10,), p=[1./3, 2./3]) array([0, 1, 1, 1, 1, 0, 0, 0, 0, 0])
stackoverflow.com
**ValueError: Unknown label type: &#39;unknown&#39;** **Top answer** Your y is of type object, so sklearn cannot recognize its type. Add the line y=y.astype('int') right after the line y = train[:, 1].
stackoverflow.com
**How to perform element-wise Boolean operations on NumPy arrays** **Top answer** Try this: mask = (foo < 40) | (foo > 60) Note: the __or__ method in an object overloads the bitwise or operator (|), not the Boolean or operator.
stackoverflow.com
**Python&#39;s sum vs. NumPy&#39;s numpy.sum** **Top answer** I got curious and timed it. numpy.sum seems much faster for numpy arrays, but much slower on lists. import numpy as np import timeit x = range(1000) # or #x = np.random.standard_normal(1000) def pure_sum(): return sum(x) def numpy_sum(): return np.sum(x) n = 10000 t1 = timeit.timeit(pure_sum, number = n) print 'Pure Python Sum:', t1 t2 = timeit.timeit(numpy_sum, number = n) print 'Numpy Sum:', t2 Result when x = range(1000): Pure Python Sum: 0.445913167735 Numpy Sum: 8.54926219673 Result when x = np.random.standard_normal(1000): Pure Python Sum: 12.1442425643 Numpy Sum: 0.303303771848 I am using Python 2.7.2 and Numpy 1.6.1
stackoverflow.com
**How to round a numpy array?** **Top answer** Numpy provides two identical methods to do this. Either use np.round(data, 2) or np.around(data, 2) as they are equivalent. See the documentation for more information. Examples: >>> import numpy as np >>> a = np.array([0.015, 0.235, 0.112]) >>> np.round(a, 2) array([0.02, 0.24, 0.11]) >>> np.around(a, 2) array([0.02, 0.24, 0.11]) >>> np.round(a, 1) array([0. , 0.2, 0.1])
stackoverflow.com
**TypeError: only length-1 arrays can be converted to Python scalars while plot showing** **Top answer** The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead. np.int was an alias for the built-in int, which is deprecated in numpy v1.20. The argument for int should be a scalar and it does not accept array-like objects. In general, if you want to apply a function to each element of the array, you can use np.vectorize: import numpy as np import matplotlib.pyplot as plt def f(x): return int(x) f2 = np.vectorize(f) x = np.arange(1, 15.1, 0.1) plt.plot(x, f2(x)) plt.show() You can skip the definition of f(x) and just pass the function int to the vectorize function: f2 = np.vectorize(int). Note that np.vectorize is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int) as @FFT suggests).
stackoverflow.com
**What does &quot;.T&quot; mean for a Numpy array?** **Top answer** The .T accesses the attribute T of the object, which happens to be a NumPy array. The T attribute is the transpose of the array, see the documentation. Apparently you are creating random coordinates in the plane. The output of multivariate_normal() might look like this: >>> np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]], 5) array([[ 0.59589335, 0.97741328], [-0.58597307, 0.56733234], [-0.69164572, 0.17840394], [-0.24992978, -2.57494471], [ 0.38896689, 0.82221377]]) The transpose of this matrix is: array([[ 0.59589335, -0.58597307, -0.69164572, -0.24992978, 0.38896689], [ 0.97741328, 0.56733234, 0.17840394, -2.57494471, 0.82221377]]) which can be conveniently separated in x and y parts by sequence unpacking.
stackoverflow.com
**pandas equivalent of np.where** **Top answer** Try: (df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B']) The difference between the numpy where and DataFrame where is that the default values are supplied by the DataFrame that the where method is being called on (docs). I.e. np.where(m, A, B) is roughly equivalent to A.where(m, B) If you wanted a similar call signature using pandas, you could take advantage of the way method calls work in Python: pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B']) or without kwargs (Note: that the positional order of arguments is different from the numpy where argument order): pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
stackoverflow.com
**SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe** **Top answer** you can also use sort_values(), groupby() and finally cumcount() + 1: df['RN'] = df.sort_values(['data1','data2'], ascending=[True,False]) \ .groupby(['key1']) \ .cumcount() + 1 print(df) yields: data1 data2 key1 RN 0 1 1 a 1 1 2 10 a 2 2 2 2 a 3 3 3 3 b 1 4 3 30 a 4 PS tested with pandas 0.18
stackoverflow.com
**Numpy slice of arbitrary dimensions** **Top answer** There is ... or Ellipsis, which does exactly this: slice = myarray[..., i] Ellipsis is the python object, if you should want to use it outside the square bracket notation.
stackoverflow.com
**How can I upgrade NumPy?** **Top answer** When you already have an older version of NumPy, use this: pip install numpy --upgrade If it still doesn't work, try: pip install numpy --upgrade --ignore-installed
stackoverflow.com
**Count all values in a matrix less than a value** **Top answer** This is very straightforward with boolean arrays: p31 = numpy.asarray(o31) za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements
stackoverflow.com
**In Python NumPy what is a dimension and axis?** **Top answer** In numpy arrays, dimensionality refers to the number of axes needed to index it, not the dimensionality of any geometrical space. For example, you can describe the locations of points in 3D space with a 2D array: array([[0, 0, 0], [1, 2, 3], [2, 2, 2], [9, 9, 9]]) Which has shape of (4, 3) and dimension 2. But it can describe 3D space because the length of each row (axis 1) is three, so each row can be the x, y, and z component of a point's location. The length of axis 0 indicates the number of points (here, 4). However, that is more of an application to the math that the code is describing, not an attribute of the array itself. In mathematics, the dimension of a vector would be its length (e.g., x, y, and z components of a 3d vector), but in numpy, any "vector" is really just considered a 1d array of varying length. The array doesn't care what the dimension of the space (if any) being described is. You can play around with this, and see the number of dimensions and shape of an array like so: In [262]: a = np.arange(9) In [263]: a Out[263]: array([0, 1, 2, 3, 4, 5, 6, 7, 8]) In [264]: a.ndim # number of dimensions Out[264]: 1 In [265]: a.shape Out[265]: (9,) In [266]: b = np.array([[0,0,0],[1,2,3],[2,2,2],[9,9,9]]) In [267]: b Out[267]: array([[0, 0, 0], [1, 2, 3], [2, 2, 2], [9, 9, 9]]) In [268]: b.ndim Out[268]: 2 In [269]: b.shape Out[269
stackoverflow.com
**Resampling a numpy array representing an image** **Top answer** Based on your description, you want scipy.ndimage.zoom. Bilinear interpolation would be order=1, nearest is order=0, and cubic is the default (order=3). zoom is specifically for regularly-gridded data that you want to resample to a new resolution. As a quick example: import numpy as np import scipy.ndimage x = np.arange(9).reshape(3,3) print 'Original array:' print x print 'Resampled by a factor of 2 with nearest interpolation:' print scipy.ndimage.zoom(x, 2, order=0) print 'Resampled by a factor of 2 with bilinear interpolation:' print scipy.ndimage.zoom(x, 2, order=1) print 'Resampled by a
stackoverflow.com
**Histogram values of a Pandas Series** **Top answer** You just need to use the histogram function of NumPy: import numpy as np count, division = np.histogram(series) where division is the automatically calculated border for your bins and count is the population inside each bin. If you need to fix a certain number of bins, you can use the argument bins and specify a number of bins, or give it directly the boundaries between each bin. count, division = np.histogram(series, bins = [-201,-149,949,1001]) to plot the results you can use the matplotlib function hist, but if you are working in pandas each Series has its own handle to the hist function, and you can give it the chosen binning: series.hist(bins=division) Edit: As mentioned by another poster, Pandas is built on top of NumPy. Since OP is explicitly using Pandas, we can do away with the additional import by accessing NumPy through Pandas: count, division = pd.np.histogram(series)
stackoverflow.com
**Difference between a -= b and a = a - b in Python** **Top answer** Note: using in-place operations on NumPy arrays that share memory in no longer a problem in version 1.13.0 onward (see details here). The two operation will produce the same result. This answer only applies to earlier versions of NumPy. Mutating arrays while they're being used in computations can lead to unexpected results! In the example in the question, subtraction with -= modifies the second element of a and then immediately uses that modified second element in the operation on the third element of a. Here is what happens with a[1:] -= a[:-1] step by step: a is the array with the data [1, 2, 3]. We have two views onto this data: a[1:] is [2, 3], and a[:-1] is [1, 2]. The in-place subt
stackoverflow.com
**How can I get descriptive statistics of a NumPy array?** **Top answer** import pandas as pd import numpy as np df_describe = pd.DataFrame(dataset) df_describe.describe() please note that dataset is your np.array to describe. import pandas as pd import numpy as np df_describe = pd.DataFrame('your np.array') df_describe.describe()
stackoverflow.com
**Numpy: Creating a complex array from 2 real ones?** **Top answer** This seems to do what you want: numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data) Here is another solution: # The ellipsis is equivalent here to ":,:,:"... numpy.vectorize(complex)(Data[...,0], Data[...,1]) And yet another simpler solution: Data[...,0] + 1j * Data[...,1] PS: If you want to save memory (no intermediate array): result = 1j*Data[...,1]; result += Data[...,0] devS' solution below is also fast.
stackoverflow.com
**What does .shape[] do in &quot;for i in range(Y.shape[0])&quot;?** **Top answer** The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n. In [46]: Y = np.arange(12).reshape(3,4) In [47]: Y Out[47]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [48]: Y.shape Out[48]: (3, 4) In [49]: Y.shape[0] Out[49]: 3
stackoverflow.com
**Fitting a Normal distribution to 1D data** **Top answer** You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows. import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt # Generate some data for this demonstration. data = norm.rvs(10.0, 2.5, size=500) # Fit a normal distribution to the data: mu, std = norm.fit(data) # Plot the histogram. plt.hist(data, bins=25, density=True, alpha=0.6, color='g') # Plot the PDF. xmin, xmax = plt.xlim() x = np.linspace(xmin, xmax, 100) p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2) title = "Fit results: mu = %.2f, std = %.2f" % (mu, std) plt.title(title) plt.show() Here's the plot generated by the script:
stackoverflow.com
**How to calculate the sum of all columns of a 2D numpy array (efficiently)** **Top answer** Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns: >>> import numpy as np >>> a = np.arange(12).reshape(4,3) >>> a.sum(axis=0) array([18, 22, 26]) Or, to sum over rows: >>> a.sum(axis=1) array([ 3, 12, 21, 30]) Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter. From the Tentative Numpy Tutorial: Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:
stackoverflow.com
**load csv into 2D matrix with numpy for plotting** **Top answer** Pure numpy numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1) Check out the loadtxt documentation. You can also use python's csv module: import csv import numpy reader = csv.reader(open("test.csv", "rb"), delimiter=",") x = list(reader) result = numpy.array(x).astype("float") You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line: result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float") Added Hint: You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.
stackoverflow.com
**Concatenate Numpy arrays without copying** **Top answer** The memory belonging to a Numpy array must be contiguous. If you allocated the arrays separately, they are randomly scattered in memory, and there is no way to represent them as a view Numpy array. If you know beforehand how many arrays you need, you can instead start with one big array that you allocate beforehand, and have each of the small arrays be a view to the big array (e.g. obtained by slicing).
stackoverflow.com
**How can I tell if NumPy creates a view or a copy?** **Top answer** This question is very similar to a question that I asked a while back: You can check the base attribute. a = np.arange(50) b = a.reshape((5, 10)) print (b.base is a) However, that's not perfect. You can also check to see if they share memory using np.may_share_memory. print (np.may_share_memory(a, b)) There's also the flags attribute that you can check: print (b.flags['OWNDATA']) #False -- apparently this is a view e = np.ravel(b[:, 2]) print (e.flags['OWNDATA']) #True -- Apparently this is a new numpy object. But this last one seems a little fishy to me, although I can't quite put my finger on why...
stackoverflow.com
**sparse 3d matrix/array in Python?** **Top answer** Happy to suggest a (possibly obvious) implementation of this, which could be made in pure Python or C/Cython if you've got time and space for new dependencies, and need it to be faster. A sparse matrix in N dimensions can assume most elements are empty, so we use a dictionary keyed on tuples: class NDSparseMatrix: def __init__(self): self.elements = {} def addValue(self, tuple, value): self.elements[tuple] = value def readValue(self, tuple): try: value = self.elements[tuple] except KeyError: # could also be 0.0 if using floats... value = 0 return value and you would use it like so: sparse = NDSparseMatrix() sparse.addValue((1,2,3), 15.7) should_be_zero = sparse.readValue((1,5,13)) You could make this implementation more robust by verifying that the input is in fact a tuple, and that it contains only integers, but that will just slow things down so I wouldn't worry unless you're releasing your code to the world later. EDIT - a Cython
stackoverflow.com
**Importing PNG files into Numpy?** **Top answer** According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.v3.imread instead. Example: import imageio.v3 as iio im = iio.imread('my_image.png') print(im.shape) You can also use imageio to load from fancy sources: im = iio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png') Edit: To load all of the *.png files in a specific folder, you could use the glob package: import imageio.v3 as iio import glob for im_path in glob.glob("path/to/folder/*.png"): im = iio.imread(im_path) print(im.shape) # do whatever with the image here
stackoverflow.com
**How to zip two 1d numpy array to 2d numpy array** **Top answer** If you have numpy arrays you can use dstack(): import numpy as np a = np.array([1,2,3,4,5]) b = np.array([6,7,8,9,10]) c = np.dstack((a,b)) #or d = np.column_stack((a,b)) >>> c array([[[ 1, 6], [ 2, 7], [ 3, 8], [ 4, 9], [ 5, 10]]]) >>> d array([[ 1, 6], [ 2, 7], [ 3, 8], [ 4, 9], [ 5, 10]]) >>> c.shape (1, 5, 2) >>> d.shape (5, 2)
stackoverflow.com
**Find out the percentage of missing values in each column in the given dataset** **Top answer** How about this? I think I actually found something similar on here once before, but I'm not seeing it now... percent_missing = df.isnull().sum() * 100 / len(df) missing_value_df = pd.DataFrame({'column_name': df.columns, 'percent_missing': percent_missing}) And if you want the missing percentages sorted, follow the above with: missing_value_df.sort_values('percent_missing', inplace=True) As mentioned in the comments, you may also be able to get by with just the first line in my code above, i.e.: percent_missing = df.isnull().sum() * 100 / len(df)
stackoverflow.com
**ValueError: numpy.dtype has the wrong size, try recompiling** **Top answer** (to expand a bit on my comment) Numpy developers follow in general a policy of keeping a backward compatible binary interface (ABI). However, the ABI is not forward compatible. What that means: A package, that uses numpy in a compiled extension, is compiled against a specific version of numpy. Future version of numpy will be compatible with the compiled extension of the package (for exception see below). Distributers of those other packages do not need to recompile their package against a newer versions of numpy and users do not need to update these other packages, when users update to a newer version of numpy. However, this does not go in the other direction. If a package is compiled against a specific numpy version, say 1.7, then there is no guarantee that the binaries of that package will work with older numpy versions, say 1.6, and very often or most of the time they will not. The binary distribution of packages like pandas and statsmodels, that are compiled against a recent version of numpy, will not work when an older version of numpy is installed. Some packages, for example matplotlib, if I remember cor
stackoverflow.com
**Does Numpy automatically detect and use GPU?** **Top answer** Does Numpy/Python automatically detect the presence of GPU and utilize it to speed up matrix computation (e.g. numpy.multiply, numpy.linalg.inv, ... etc)? No. Or do I have code in a specific way to exploit the GPU for fast computation? Yes. Search for Numba, CuPy, Theano, PyTorch or PyCUDA for different paradigms for accelerating Python with GPUs.
stackoverflow.com
**What does x[x &lt; 2] = 0 mean in Python?** **Top answer** This only makes sense with NumPy arrays. The behavior with lists is useless, and specific to Python 2 (not Python 3). You may want to double-check if the original object was indeed a NumPy array (see further below) and not a list. But in your code here, x is a simple list. Since x < 2 is False i.e 0, therefore x[x<2] is x[0] x[0] gets changed. Conversely, x[x>2] is x[True] or x[1] So, x[1] gets changed. Why does this happen? The rules for comparison are: When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers). When you order a numeric and a non-numeric type, the numeric type comes first. When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames: So, we have the following order numeric < list < string < tuple See the accepted answer for How does Python compare string and int?. If x is a NumPy array, then the syntax makes more sense because of boolean array indexing. In that case, x < 2 isn't a boolean at all; it's an array of booleans representing whether each element of x was less than 2. x[x < 2] = 0 then selects the elements of x that were less than 2 and sets those cells to 0. See Indexing. >>> x = np.array([1., -1., -2., 3]) >>> x < 0 array([False, True, True, False], dtype=bool) >>> x[x < 0] += 20 # All elements < 0 get increased by 20 >>> x array([ 1., 19., 18., 3.]) # Only elements < 0 are affected
stackoverflow.com
**Concatenate two NumPy arrays vertically** **Top answer** Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate. this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3): a = np.array([[1,5,9], [2,6,10]]) b = np.array([[3,7,11], [4,8,12]]) concatenates along the 1st axis (rows of the 1st, then rows of the 2nd): np.concatenate((a,b), axis=0) array([[ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11], [ 4, 8, 12]]) concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd): np.concatenate((a, b), axis=1) array([[ 1, 5, 9, 3, 7, 11], [ 2, 6, 10, 4, 8, 12]]) to obtain the output you presented, you can use vstack a = np.array([1,2,3]) b = np.array([4,5,6]) np.vstack((a, b)) array([[1, 2, 3], [4, 5, 6]]) You can still do it with concatenate, but you need to reshape them first: np.concatenate((a.reshape(1,3), b.reshape(1,3))) array([[1, 2, 3], [4, 5, 6]]) Finally, as proposed in the comments, one way to reshape them is to use newaxis: np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))
stackoverflow.com
**Calculating the area under a curve given a set of coordinates, without knowing the function** **Top answer** The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simpson) rules. Here's a simple example. In both trapz and simpson, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units. import numpy as np from scipy.integrate import simpson from numpy import trapz # The y values. A numpy array is used here, # but a python list could also be used. y = np.array([5, 20, 4, 18, 19, 18, 7, 4]) # Compute the area using the composite trapezoidal rule. area = trapz(y, dx=5) print("area =", area) # Compute the area using the composite Simpson's rule. area = simpson(y, dx=5) print("area =", area) Output: area = 452.5 area = 460.0
stackoverflow.com