text
stringlengths
31
26.7k
source
stringclasses
4 values
**How do I print the full NumPy array, without truncation?** **Top answer** Use numpy.set_printoptions: import sys import numpy numpy.set_printoptions(threshold=sys.maxsize)
stackoverflow.com
**How do I get indices of N maximum values in a NumPy array?** **Top answer** Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do >>> a = np.array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) >>> a array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) >>> ind = np.ar...
stackoverflow.com
**Dump a NumPy array into a csv file** **Top answer** numpy.savetxt saves an array to a text file. import numpy a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpy.savetxt("foo.csv", a, delimiter=",")
stackoverflow.com
**How can the Euclidean distance be calculated with NumPy?** **Top answer** Use numpy.linalg.norm: dist = numpy.linalg.norm(a-b) This works because the Euclidean distance is the l2 norm, and the default value of the ord parameter in numpy.linalg.norm is 2. For more theory, see Introduction to Data Mining:
stackoverflow.com
**Convert Pandas dataframe to NumPy array** **Top answer** Use df.to_numpy() It's better than df.values, here's why.* It's time to deprecate your usage of values and as_matrix(). pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects: to_numpy(), which is defined on Index, Series, an...
stackoverflow.com
**Most efficient way to map function over numpy array** **Top answer** I've tested all suggested methods plus np.array(list(map(f, x))) with perfplot (a small project of mine). Message #1: If you can use numpy's native functions, do that. If the function you're trying to vectorize already is vectorized (like the x**...
stackoverflow.com
**What does -1 mean in numpy reshape?** **Top answer** The criterion to satisfy for providing the new shape is that 'The new shape should be compatible with the original shape' numpy allow us to give one of new shape parameter as -1 (eg: (2,-1) or (-1,3) but not (-1, -1)). It simply means that it is an unknown dimensi...
stackoverflow.com
**How do I access the ith column of a NumPy multidimensional array?** **Top answer** With: test = np.array([[1, 2], [3, 4], [5, 6]]) To access column 0: >>> test[:, 0] array([1, 3, 5]) To access row 0: >>> test[0, :] array([1, 2]) This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at ...
stackoverflow.com
**How do I count the occurrence of a certain item in an ndarray?** **Top answer** Using numpy.unique: import numpy a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4]) unique, counts = numpy.unique(a, return_counts=True) >>> dict(zip(unique, counts)) {0: 7, 1: 4, 2: 1, 3: 2, 4: 1} Non-numpy method using co...
stackoverflow.com
**Is there a NumPy function to return the first index of something in an array?** **Top answer** Yes, given an array, array, and a value, item to search for, you can use np.where as: itemindex = numpy.where(array == item) The result is a tuple with first all the row indices, then all the column indices. For example, ...
stackoverflow.com
**Pandas read_csv: low_memory and dtype options** **Top answer** The deprecated low_memory option The low_memory option is not properly deprecated, but it should be, since it does not actually do anything differently[source] The reason you get this low_memory warning is because guessing dtypes for each column is very ...
stackoverflow.com
**How can I use the apply() function for a single column?** **Top answer** Given a sample dataframe df as: a b 0 1 2 1 2 3 2 3 4 3 4 5 what you want is: df['a'] = df['a'].apply(lambda x: x + 1) that returns: a b 0 2 2 1 3 3 2 4 4 3 5 5
stackoverflow.com
**How do I read CSV data into a record array in NumPy?** **Top answer** Use numpy.genfromtxt() by setting the delimiter kwarg to a comma: from numpy import genfromtxt my_data = genfromtxt('my_file.csv', delimiter=',')
stackoverflow.com
**What are the advantages of NumPy over regular Python lists?** **Top answer** NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writ...
stackoverflow.com
**Sorting arrays in NumPy by column** **Top answer** To sort by the second column of a: a[a[:, 1].argsort()]
stackoverflow.com
**What does numpy.random.seed(0) do?** **Top answer** np.random.seed(0) makes the random numbers predictable >>> numpy.random.seed(0) ; numpy.random.rand(4) array([ 0.55, 0.72, 0.6 , 0.54]) >>> numpy.random.seed(0) ; numpy.random.rand(4) array([ 0.55, 0.72, 0.6 , 0.54]) With the seed reset (every time), the sam...
stackoverflow.com
**How do I create a new column where the values are selected based on an existing column?** **Top answer** If you only have two choices to select from then use np.where: df['color'] = np.where(df['Set']=='Z', 'green', 'red') For example, import pandas as pd import numpy as np df = pd.DataFrame({'Type':list('ABBC'), ...
stackoverflow.com
**What is the purpose of meshgrid in NumPy?** **Top answer** The purpose of meshgrid is to create a rectangular grid out of an array of x values and an array of y values. So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a...
stackoverflow.com
**Find nearest value in numpy array** **Top answer** import numpy as np def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return array[idx] Example usage: array = np.random.random(10) print(array) # [ 0.21069679 0.61290182 0.63425412 0.84635244 0.91599191...
stackoverflow.com
**How do I convert a PIL Image into a NumPy array?** **Top answer** You're not saying how exactly putdata() is not behaving. I'm assuming you're doing >>> pic.putdata(a) Traceback (most recent call last): File "...blablabla.../PIL/Image.py", line 1185, in putdata self.im.putdata(data, scale, offset) SystemError:...
stackoverflow.com
**Pretty-print a NumPy array without scientific notation and with given precision** **Top answer** Use numpy.set_printoptions to set the precision of the output: import numpy as np x = np.random.random(10) print(x) # [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732 # 0.51303098 0.4617183 0....
stackoverflow.com
**Converting between datetime, Timestamp and datetime64** **Top answer** You can just use the pd.Timestamp constructor. The following diagram may be useful for this and related questions.
stackoverflow.com
**NumPy array is not JSON serializable** **Top answer** I regularly "jsonify" np.arrays. Try using the ".tolist()" method on the arrays first, like this: import numpy as np import codecs, json a = np.arange(10).reshape(2,5) # a 2 by 5 array b = a.tolist() # nested lists with same data, indices file_path = "/path.jso...
stackoverflow.com
**What is the difference between np.array() and np.asarray()?** **Top answer** The definition of asarray is: def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order) So it is like array, except it has fewer options, and copy=False. array has copy=True by default. The main differenc...
stackoverflow.com
**How do I add an extra column to a NumPy array?** **Top answer** np.r_[...] (docs) and np.c_[...] (docs) are useful alternatives to np.vstack and np.hstack. Note that they use square brackets [] instead of parentheses (). Some examples: : import numpy as np : N = 3 : A = np.eye(N) : np.c_[ A, np.ones(N) ] ...
stackoverflow.com
**Comparing two NumPy arrays for equality, element-wise** **Top answer** (A==B).all() test if all values of array (A==B) are True. Note: maybe you also want to test A and B shape, such as A.shape == B.shape Special cases and alternatives (from dbaupp's answer and yoavram's comment) It should be noted that: this solu...
stackoverflow.com
**What is the difference between flatten and ravel functions in numpy?** **Top answer** The current API is that: flatten always returns a copy. ravel returns a contiguous view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modif...
stackoverflow.com
**How do I create an empty array and then append to it in NumPy?** **Top answer** That is the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. To append rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating ga...
stackoverflow.com
**What are the differences between numpy arrays and matrices? Which one should I use?** **Top answer** Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays. The main advantage of...
stackoverflow.com
**Numpy array dimensions** **Top answer** Use .shape to obtain a tuple of array dimensions: >>> a.shape (2, 2)
stackoverflow.com
**Saving a Numpy array as an image** **Top answer** Using PIL, save a NumPy array arr by doing: from PIL import Image im = Image.fromarray(arr) im.save("your_file.jpeg") See the docs for available data formats, including JPEG, PNG, and so on.
stackoverflow.com
**Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?** **Top answer** Specify data, index and columns to the DataFrame constructor, as follows: >>> pd.DataFrame(data=data[1:,1:], # values ... index=data[1:,0], # 1st column as index ... ...
stackoverflow.com
**Difference between numpy.array shape (R, 1) and (R,)** **Top answer** 1. The meaning of shapes in NumPy You write, "I know literally it's list of numbers and list of lists where all list contains only a number" but that's a bit of an unhelpful way to think about it. The best way to think about NumPy arrays is that t...
stackoverflow.com
**Convert NumPy array to Python list** **Top answer** Use tolist(): >>> import numpy as np >>> np.array([[1,2,3],[4,5,6]]).tolist() [[1, 2, 3], [4, 5, 6]] Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you...
stackoverflow.com
**Simple Digit Recognition OCR in OpenCV-Python** **Top answer** Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR...
stackoverflow.com
**Concatenating two one-dimensional NumPy arrays** **Top answer** Use: np.concatenate([a, b]) The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments. From the NumPy documentation: numpy.concatenate((a1, a2, ...), axis=0) Join a sequence of arrays together. It was trying to ...
stackoverflow.com
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()** **Top answer** If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them: a & b That returns a Boolean array. To reduce this to a single Boolean value, use either (a & b).any() o...
stackoverflow.com
**NumPy array initialization (fill with identical values)** **Top answer** NumPyΒ 1.8 introduced np.full(), which is a more direct method than empty() followed by fill() for creating an array filled with a certain value: >>> np.full((3, 5), 7) array([[ 7., 7., 7., 7., 7.], [ 7., 7., 7., 7., 7.], [...
stackoverflow.com
**Frequency counts for unique values in a NumPy array** **Top answer** Use numpy.unique with return_counts=True (for NumPy 1.9+): import numpy as np x = np.array([1,1,1,2,2,2,5,25,1,1]) unique, counts = np.unique(x, return_counts=True) >>> print(np.asarray((unique, counts)).T) [[ 1 5] [ 2 3] [ 5 1] [25 1]...
stackoverflow.com
**What is the difference between ndarray and array in NumPy?** **Top answer** numpy.array is just a convenience function to create an ndarray; it is not a class itself. You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray: Arrays should be const...
stackoverflow.com
**Dropping infinite values from dataframes in pandas?** **Top answer** First replace() infs with NaN: df.replace([np.inf, -np.inf], np.nan, inplace=True) and then drop NaNs via dropna(): df.dropna(subset=["col1", "col2"], how="all", inplace=True) For example: >>> df = pd.DataFrame({"col1": [1, np.inf, -np.inf], "co...
stackoverflow.com
**How do I use np.newaxis?** **Top answer** Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus, 1D array will become 2D array 2D array will become 3D array 3D array will become 4D array 4D array will become 5D array and so on.. Here is a ...
stackoverflow.com
**Converting numpy dtypes to native python types** **Top answer** Use val.item() to convert most NumPy values to a native Python type: import numpy as np # for example, numpy.float32 -> python float val = np.float32(0) pyval = val.item() print(type(pyval)) # <class 'float'> # and similar... type(np.float64(0...
stackoverflow.com
**How do I remove NaN values from a NumPy array?** **Top answer** To remove NaN values from a NumPy array x: x = x[~numpy.isnan(x)] Explanation The inner function numpy.isnan returns a boolean/logical array which has the value True everywhere that x is not-a-number. Since we want the opposite, we use the logical-not ...
stackoverflow.com
**How do I check which version of NumPy I&#39;m using?** **Top answer** import numpy numpy.version.version
stackoverflow.com
**How do I convert a numpy array to (and display) an image?** **Top answer** Use plt.imshow to create the figure, and plt.show to display it: from matplotlib import pyplot as plt plt.imshow(data, interpolation='nearest') plt.show() For Jupyter notebooks, add this line before importing matplotlib: %matplotlib inline ...
stackoverflow.com
**Most efficient way to reverse a numpy array** **Top answer** reversed_arr = arr[::-1] gives a reversed view into the original array arr. Any changes made to the original array arr will also be immediately visible in reversed_arr. The underlying data buffers for arr and reversed_arr are shared, so creating this vie...
stackoverflow.com
**Understanding NumPy&#39;s einsum** **Top answer** (Note: this answer is based on a short blog post about einsum I wrote a while ago.) What does einsum do? Imagine that we have two multi-dimensional arrays, A and B. Now let's suppose we want to... multiply A with B in a particular way to create new array of products...
stackoverflow.com
**Split (explode) pandas dataframe string entry to separate rows** **Top answer** UPDATE 3: it makes more sense to use Series.explode() / DataFrame.explode() methods (implemented in Pandas 0.25.0 and extended in Pandas 1.3.0 to support multi-column explode) as is shown in the usage example: for a single column: In [1]...
stackoverflow.com
**Convert 2D float array to 2D int array in NumPy** **Top answer** Use the astype method. >>> x = np.array([[1.0, 2.3], [1.3, 2.9]]) >>> x array([[ 1. , 2.3], [ 1.3, 2.9]]) >>> x.astype(int) array([[1, 2], [1, 2]])
stackoverflow.com
**How to remove specific elements in a numpy array** **Top answer** Use numpy.delete(), which returns a new array with sub-arrays along an axis deleted. numpy.delete(a, index) For your specific question: import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) index = [2, 3, 6] new_a = np.delete(a, index) prin...
stackoverflow.com
**Convert array of indices to one-hot encoded array in NumPy** **Top answer** Create a zeroed array b with enough columns, i.e. a.max() + 1. Then, for each row i, set the a[i]th column to 1. >>> a = np.array([1, 0, 3]) >>> b = np.zeros((a.size, a.max() + 1)) >>> b[np.arange(a.size), a] = 1 >>> b array([[ 0., 1., 0....
stackoverflow.com
**Better way to shuffle two numpy arrays in unison** **Top answer** Your can use NumPy's array indexing: def unison_shuffled_copies(a, b): assert len(a) == len(b) p = numpy.random.permutation(len(a)) return a[p], b[p] This will result in creation of separate unison-shuffled arrays.
stackoverflow.com
**Convert a tensor to numpy array in Tensorflow?** **Top answer** TensorFlow 2.x Eager Execution is enabled by default, so just call .numpy() on the Tensor object. import tensorflow as tf a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) a.numpy() # array([[1, 2], # [3, 4]], dtype=int32) b....
stackoverflow.com
**Error &quot;Import Error: No module named numpy&quot; on Windows** **Top answer** You can simply use pip install numpy Or for python3, use pip3 install numpy
stackoverflow.com
**ValueError: setting an array element with a sequence** **Top answer** Possible reason 1: trying to create a jagged array You may be creating an array from a list that isn't shaped like a multi-dimensional array: numpy.array([[1, 2], [2, 3, 4]]) # wrong! numpy.array([[1, 2], [2, [3, 4]]]) # wrong! In ...
stackoverflow.com
**How to take column-slices of dataframe in pandas** **Top answer** 2017 Answer - pandas 0.20: .ix is deprecated. Use .loc See the deprecation in the docs .loc uses label based indexing to select both rows and columns. The labels being the values of the index or the columns. Slicing with .loc includes the last element...
stackoverflow.com
**How to normalize a numpy array to a unit vector** **Top answer** If you're using scikit-learn you can use sklearn.preprocessing.normalize: import numpy as np from sklearn.preprocessing import normalize x = np.random.rand(1000)*10 norm1 = x / np.linalg.norm(x) norm2 = normalize(x[:,np.newaxis], axis=0).ravel() print...
stackoverflow.com
**How can I map True/False to 1/0 in a Pandas DataFrame?** **Top answer** A succinct way to convert a single column of boolean values to a column of integers 1 or 0: df["somecolumn"] = df["somecolumn"].astype(int)
stackoverflow.com
**How do I calculate percentiles with python/numpy?** **Top answer** NumPy has np.percentile(). import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) # return 50th percentile, i.e. median. >>> print(p) 3.0 SciPy has scipy.stats.scoreatpercentile(), in addition to many other statistical goodies.
stackoverflow.com
**How to implement the Softmax function in Python?** **Top answer** They're both correct, but yours is preferred from the point of view of numerical stability. You start with e ^ (x - max(x)) / sum(e^(x - max(x)) By using the fact that a^(b - c) = (a^b)/(a^c) we have = e ^ x / (e ^ max(x) * sum(e ^ x / e ^ max(x))) ...
stackoverflow.com
**Moving average or running mean** **Top answer** NOTE: More efficient solutions may include scipy.ndimage.uniform_filter1d (see this answer), or using newer libraries including talib's talib.MA. Use np.convolve: np.convolve(x, np.ones(N)/N, mode='valid') Explanation The running mean is a case of the mathematical ...
stackoverflow.com
**How do I create a numpy array of all True or all False?** **Top answer** The answer: numpy.full((2, 2), True) Explanation: numpy creates arrays of all ones or all zeros very easily: e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2)) Since True and False are represented in Python as 1 and 0, respectively, we have only ...
stackoverflow.com
**Create numpy matrix filled with NaNs** **Top answer** You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once: >>> a = numpy.empty((3,3,)) >>> a[:] = numpy.nan >>> a array([[ NaN, NaN, NaN], [ NaN, NaN, NaN], [ NaN, NaN, NaN]])...
stackoverflow.com
**How to smooth a curve for a dataset** **Top answer** I prefer a Savitzky-Golay filter. It's available in scipy here. It uses least squares to regress a small window of your data onto a polynomial, then uses the polynomial to estimate the point in the center of the window. Finally the window is shifted forward by one...
stackoverflow.com
**Take multiple lists into dataframe** **Top answer** I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this): import pandas as pd lst1 = range(100) lst2 = range(100) lst3 = range(100) ...
stackoverflow.com
**How can I check whether a numpy array is empty or not?** **Top answer** You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array: import numpy as np a = np.array([]) if a.size == 0: # Do something when `a` is empty
stackoverflow.com
**Replacing Pandas or Numpy Nan with a None to use with MysqlDB** **Top answer** df = df.replace({np.nan: None}) Note: For pandas versions <1.4, this changes the dtype of all affected columns to object. To avoid that, use this syntax instead: df = df.replace(np.nan, None) Note 2: If you don't want to import numpy, n...
stackoverflow.com
**How to convert a NumPy array to PIL image applying matplotlib colormap** **Top answer** Quite a busy one-liner, but here it is: First ensure your NumPy array, myarray, is normalised with the max value at 1.0. Apply the colormap directly to myarray. Rescale to the 0-255 range. Convert to integers, using np.uint8(). ...
stackoverflow.com
**Transposing a 1D NumPy array** **Top answer** It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.) If you want to turn your 1D vector into a 2D array and then transpo...
stackoverflow.com
**Replace all elements of NumPy array that are greater than some value** **Top answer** I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray named arr, you can replace all elements >255 with a value x as follows: arr[arr > 255] = x I ran this on my...
stackoverflow.com
**Relationship between SciPy and NumPy** **Top answer** Last time I checked it, the scipy __init__ method executes a from numpy import * so that the whole numpy namespace is included into scipy when the scipy module is imported. The log10 behavior you are describing is interesting, because both versions are coming fr...
stackoverflow.com
**Counting unique values in a column in pandas dataframe like in Qlik?** **Top answer** Count distinct values, use nunique: df['hID'].nunique() 5 Count only non-null values, use count: df['hID'].count() 8 Count total values including null values, use the size attribute: df['hID'].size 8 Edit to add condition Use bo...
stackoverflow.com
**Is it possible to use argsort in descending order?** **Top answer** If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are: (-avgDists).argsort()[:n] Another way to reason about this, as mentioned in the comments, is to observe t...
stackoverflow.com
**List of lists into numpy array** **Top answer** If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options: 1) Make an array of arrays: x=[[1,2],[1,2,3],[1]] y=numpy.array([numpy.array(xi) for xi in x]) type(y) >>...
stackoverflow.com
**np.mean() vs np.average() in Python NumPy?** **Top answer** np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code: Mean, Average np.mean: try: mean = a.mean except AttributeError: return _wrapit(a, 'mean', axis, dtype, out) return mean(axis...
stackoverflow.com
**How to count the number of true elements in a NumPy bool array** **Top answer** You have multiple options. Two options are the following. boolarr.sum() numpy.count_nonzero(boolarr) Here's an example: >>> import numpy as np >>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool) >>> boolarr array([[...
stackoverflow.com
**ImportError: numpy.core.multiarray failed to import** **Top answer** I was getting the same error and was able to solve it by updating my numpy installation to 1.8.0: pip install -U numpy
stackoverflow.com
**Find unique rows in numpy.array** **Top answer** As of NumPy 1.13, one can simply choose the axis for selection of unique values in any N-dim array. To get unique rows, use np.unique as follows: unique_rows = np.unique(original_array, axis=0)
stackoverflow.com
**Suppress Scientific Notation in Numpy When Creating Array From Nested List** **Top answer** This is what you need: np.set_printoptions(suppress=True) Here is the documentation which says suppress: bool, optional If True, always print floating point numbers using fixed point notation, in which case numbers equal to...
stackoverflow.com
**How do you get the magnitude of a vector in Numpy?** **Top answer** The function you're after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array -- say x.norm() -- but oh well). import numpy as np x = np.array([1,2,3,4,5]) np.linalg.norm(x) You can also feed in an optional ord for ...
stackoverflow.com
**Numpy - add row to array** **Top answer** You can do this: newrow = [1, 2, 3] A = numpy.vstack([A, newrow])
stackoverflow.com
**How to flatten only some dimensions of a numpy array** **Top answer** Take a look at numpy.reshape . >>> arr = numpy.zeros((50,100,25)) >>> arr.shape # (50, 100, 25) >>> new_arr = arr.reshape(5000,25) >>> new_arr.shape # (5000, 25) # One shape dimension can be -1. # In this case, the value is inferred from # ...
stackoverflow.com
**How to calculate rolling / moving average using python + NumPy / SciPy?** **Top answer** If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods: EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. ...
stackoverflow.com
**Python - TypeError: Object of type &#39;int64&#39; is not JSON serializable** **Top answer** You can define your own encoder to solve this problem. import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) ...
stackoverflow.com
**How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting** **Top answer** For fitting y = A + B log x, just fit y against (log x). >>> x = numpy.array([1, 7, 20, 50, 79]) >>> y = numpy.array([10, 19, 30, 35, 51]) >>> numpy.polyfit(numpy.log(x), y, 1) array([ 8.46295607, 6.61867...
stackoverflow.com
**A column-vector y was passed when a 1d array was expected** **Top answer** Change this line: model = forest.fit(train_fold, train_y) to: model = forest.fit(train_fold, train_y.values.ravel()) Explanation: .values will give the values in a numpy array (shape: (n,1)) .ravel will convert that array shape to (n, ) (i....
stackoverflow.com
**Concatenate a NumPy array to another NumPy array** **Top answer** In [1]: import numpy as np In [2]: a = np.array([[1, 2, 3], [4, 5, 6]]) In [3]: b = np.array([[9, 8, 7], [6, 5, 4]]) In [4]: np.concatenate((a, b)) Out[4]: array([[1, 2, 3], [4, 5, 6], [9, 8, 7], [6, 5, 4]]) or this: In [1]: ...
stackoverflow.com
**How do I catch a numpy warning like it&#39;s an exception (not just for testing)?** **Top answer** It seems that your configuration is using the print option for numpy.seterr: >>> import numpy as np >>> np.array([1])/0 #'warn' mode __main__:1: RuntimeWarning: divide by zero encountered in divide array([0]) >>> np....
stackoverflow.com
**&quot;Cloning&quot; row or column vectors** **Top answer** Use numpy.tile: >>> tile(array([1,2,3]), (3, 1)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) or for repeating columns: >>> tile(array([[1,2,3]]).transpose(), (1, 3)) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
stackoverflow.com
**NumPy or Pandas: Keeping array type as integer while having a NaN value** **Top answer** NaN can't be stored in an integer array. This is a known limitation of pandas at the moment; I have been waiting for progress to be made with NA values in NumPy (similar to NAs in R), but it will be at least 6 months to a year b...
stackoverflow.com
**Extracting specific columns in numpy array** **Top answer** I assume you wanted columns 1 and 9? To select multiple columns at once, use X = data[:, [1, 9]] To select one at a time, use x, y = data[:, 1], data[:, 9] With names: data[:, ['Column Name1','Column Name2']] You can get the names from data.dtype.names…...
stackoverflow.com
**Numpy first occurrence of value greater than existing value** **Top answer** This is a little faster (and looks nicer) np.argmax(aa>5) Since argmax will stop at the first True ("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save ...
stackoverflow.com
**How to add a new row to an empty numpy array** **Top answer** The way to "start" the array that you want is: arr = np.empty((0,3), int) Which is an empty array but it has the proper dimensionality. >>> arr array([], shape=(0, 3), dtype=int64) Then be sure to append along axis 0: arr = np.append(arr, np.array([[1,2...
stackoverflow.com
**ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject** **Top answer** I'm in Python 3.8.5. It sounds too simple to be real, but I had this same issue and all I did was reinstall numpy. Gone. pip install --upgrade numpy or pip uninstall numpy pi...
stackoverflow.com
**Numpy: Get random set of rows from 2D array** **Top answer** >>> A = np.random.randint(5, size=(10,3)) >>> A array([[1, 3, 0], [3, 2, 0], [0, 2, 1], [1, 1, 4], [3, 2, 2], [0, 1, 0], [1, 3, 1], [0, 4, 1], [2, 4, 2], [3, 3, 1]]) >>> idx = np.random.randint...
stackoverflow.com
**Python memory usage of numpy arrays** **Top answer** You can use array.nbytes for numpy arrays, for example: import numpy as np from sys import getsizeof a = [0] * 1024 b = np.array(a) print(getsizeof(a)) print(b.nbytes) Output: 8264 8192
stackoverflow.com
**How to install python modules without root access?** **Top answer** In most situations the best solution is to rely on the so-called "user site" location (see the PEP for details) by running: pip install --user package_name Below is a more "manual" way from my original answer, you do not need to read it if the abov...
stackoverflow.com
**Numpy where function multiple conditions** **Top answer** The best way in your particular case would just be to change your two criteria to one criterion: dists[abs(dists - r - dr/2.) <= dr/2.] It only creates one boolean array, and in my opinion is easier to read because it says, is dist within a dr or r? (Though ...
stackoverflow.com
**AttributeError: module &#39;pkgutil&#39; has no attribute &#39;ImpImporter&#39;. Did you mean: &#39;zipimporter&#39;?** **Top answer** Due to the removal of the long-deprecated pkgutil.ImpImporter class, the pip command may not work for Python 3.12. You just have to manually install pip for Python 3.12 python -m ens...
stackoverflow.com