text stringlengths 29 2.66k | source stringclasses 5
values |
|---|---|
**How to make a multidimension numpy array with a varying row size?**
**Top answer**
We are now almost 7 years after the question was asked, and your code
cells = numpy.array([[0,1,2,3], [2,3,4]])
executed in numpy 1.12.0, python 3.5, doesn't produce any error and
cells contains:
array([[0, 1, 2, 3], [2, 3, 4]], dt... | stackoverflow.com |
**How to display progress of scipy.optimize function?**
**Top answer**
As mg007 suggested, some of the scipy.optimize routines allow for a callback function (unfortunately leastsq does not permit this at the moment). Below is an example using the "fmin_bfgs" routine where I use a callback function to display the curre... | stackoverflow.com |
**Convert numpy.datetime64 to string object in python**
**Top answer**
Solution was:
import pandas as pd
ts = pd.to_datetime(str(date))
d = ts.strftime('%Y.%m.%d') | stackoverflow.com |
**Save plot to numpy array**
**Top answer**
This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot.
One way is to use fig.canvas.tostring_rgb and then numpy.fromstring with the approriate dtype. There are other ways as well, but this is the one I tend to us... | stackoverflow.com |
**Formatting floats in a numpy array**
**Top answer**
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f here means fixed-point format (not 'scientifi... | stackoverflow.com |
**Combine 3 separate numpy arrays to an RGB image in Python**
**Top answer**
rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3
To also convert floats 0 .. 1 to uint8 s,
rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256 | stackoverflow.com |
**How to use python numpy.savetxt to write strings and float number to an ASCII file?**
**Top answer**
You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):
num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s")
The default format is a float, that is the reason it was expecting a... | stackoverflow.com |
**Inverse of a matrix using numpy**
**Top answer**
The I attribute only exists on matrix objects, not ndarrays. You can use numpy.linalg.inv to invert arrays:
inverse = numpy.linalg.inv(x)
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're g... | stackoverflow.com |
**Fast punctuation removal with pandas**
**Top answer**
Setup
For the purpose of demonstration, let's consider this DataFrame.
df = pd.DataFrame({'text':['a..b?!??', '%hgh&12','abc123!!!', '$$$1234']})
df
text
0 a..b?!??
1 %hgh&12
2 abc123!!!
3 $$$1234
Below, I list the alternatives, one by one, in i... | stackoverflow.com |
**How to turn a boolean array into index array in numpy**
**Top answer**
Another option:
In [13]: numpy.where(mask)
Out[13]: (array([36, 68, 84, 92, 96, 98]),)
which is the same thing as numpy.where(mask==True). | stackoverflow.com |
**Efficient thresholding filter of an array with numpy**
**Top answer**
b = a[a>threshold] this should do
I tested as follows:
import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetim... | stackoverflow.com |
**Mesh grid functions in Python (meshgrid mgrid ogrid ndgrid)**
**Top answer**
numpy.meshgrid is modelled after Matlab's meshgrid command. It is used to vectorise functions of two variables, so that you can write
x = numpy.array([1, 2, 3])
y = numpy.array([10, 20, 30])
XX, YY = numpy.meshgrid(x, y)
ZZ = XX + YY
ZZ =... | stackoverflow.com |
**How to generate audio from a numpy array?**
**Top answer**
You can use the write function from scipy.io.wavfile to create a wav file which you can then play however you wish. Note that the array must be integers, so if you have floats, you might want to scale them appropriately:
import numpy as np
from scipy.io.wavf... | stackoverflow.com |
**Factorial in numpy and scipy**
**Top answer**
You can import them like this:
In [7]: import scipy, numpy, math
In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
Out[8]:
(<function math.factorial>,
<function math.factorial>,
<function math.factorial>)
scipy.math.factorial and numpy.math.factoria... | stackoverflow.com |
**Ignore divide by 0 warning in NumPy**
**Top answer**
You can disable the warning with numpy.seterr. Put this before the possible division by zero:
np.seterr(divide='ignore')
That'll disable zero division warnings globally. If you just want to disable them for a little bit, you can use numpy.errstate in a with claus... | stackoverflow.com |
**How can numpy be so much faster than my Fortran routine?**
**Top answer**
Your Fortran implementation suffers two major shortcomings:
You mix IO and computations (and read from the file entry by entry).
You don't use vector/matrix operations.
This implementation does perform the same operation as yours and is fa... | stackoverflow.com |
**Python Array Slice With Comma?**
**Top answer**
It is being used to extract a specific column from a 2D array.
So your example would extract column 0 (the first column) from the first 2048 rows (0 to 2047). Note however that this syntax will only work for numpy arrays and not general python lists. | stackoverflow.com |
**Iterating over arbitrary dimension of numpy.array**
**Top answer**
What you propose is quite fast, but the legibility can be improved with the clearer forms:
for i in range(c.shape[-1]):
print c[:,:,i]
or, better (faster, more general and more explicit):
for i in range(c.shape[-1]):
print c[...,i]
However,... | stackoverflow.com |
**How can I release memory after creating matplotlib figures**
**Top answer**
Did you try to run you task function several times (in a for) to be sure that not your function is leaking no matter of celery?
Make sure that django.settings.DEBUG is set False( The connection object holds all queries in memmory when DEBUG=... | stackoverflow.com |
**How does condensed distance matrix work? (pdist)**
**Top answer**
You can look at it this way: Suppose x is m by n. The possible pairs of m rows, chosen two at a time, is itertools.combinations(range(m), 2), e.g, for m=3:
>>> import itertools
>>> list(combinations(range(3),2))
[(0, 1), (0, 2), (1, 2)]
So if d = pd... | stackoverflow.com |
**Numpy ‘smart’ symmetric matrix**
**Top answer**
If you can afford to symmetrize the matrix just before doing calculations, the following should be reasonably fast:
def symmetrize(a):
"""
Return a symmetrized version of NumPy array a.
Values 0 are replaced by the array value at the symmetric
position... | stackoverflow.com |
**shuffling/permutating a DataFrame in pandas**
**Top answer**
Use numpy's random.permuation function:
In [1]: df = pd.DataFrame({'A':range(10), 'B':range(10)})
In [2]: df
Out[2]:
A B
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
In [3]: df.reindex(np.random.permutation(df.inde... | stackoverflow.com |
**How to overplot a line on a scatter plot in python?**
**Top answer**
import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt
# Sample data
x = np.arange(10)
y = 5 * x + 10
# Fit with polyfit
b, m = polyfit(x, y, 1)
plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show... | stackoverflow.com |
**Set numpy array elements to zero if they are above a specific threshold**
**Top answer**
In [7]: a = np.array([2, 23, 15, 7, 9, 11, 17, 19, 5, 3])
In [8]: a[a > 10] = 0
In [9]: a
Out[9]: array([2, 0, 0, 7, 9, 0, 0, 0, 5, 3]) | stackoverflow.com |
**What does numpy.gradient do?**
**Top answer**
Also in the documentation1:
>>> y = np.array([1, 2, 4, 7, 11, 16], dtype=np.float)
>>> j = np.gradient(y)
>>> j
array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
Gradient is defined as (change in y)/(change in x).
x, here, is the list index, so the difference between adjac... | stackoverflow.com |
**Average values in two Numpy arrays**
**Top answer**
You can create a 3D array containing your 2D arrays to be averaged, then average along axis=0 using np.mean or np.average (the latter allows for weighted averages):
np.mean( np.array([ old_set, new_set ]), axis=0 )
This averaging scheme can be applied to any (n)-d... | stackoverflow.com |
**Function to determine if two numbers are nearly equal when rounded to n significant decimal digits**
**Top answer**
As of Python 3.5, the standard way to do this (using the standard library) is with the math.isclose function.
It has the following signature:
isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
An example of usa... | stackoverflow.com |
**Sort array's rows by another array in Python**
**Top answer**
Use argsort as follows:
arr1inds = arr1.argsort()
sorted_arr1 = arr1[arr1inds[::-1]]
sorted_arr2 = arr2[arr1inds[::-1]]
This example sorts in descending order. | stackoverflow.com |
**TypeError: unhashable type: 'numpy.ndarray'**
**Top answer**
Your variable energies probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most r... | stackoverflow.com |
**How to filter numpy array by list of indices?**
**Top answer**
It looks like you just need a basic integer array indexing:
filter_indices = [1,3,5]
np.array([11,13,155,22,0xff,32,56,88])[filter_indices] | stackoverflow.com |
**Equivalent of Numpy.argsort() in basic python?**
**Top answer**
There is no built-in function, but it's easy to assemble one out of the terrific tools Python makes available:
def argsort(seq):
# http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python
retur... | stackoverflow.com |
**python pandas flatten a dataframe to a list**
**Top answer**
You can use .flatten() on the DataFrame converted to a NumPy array:
df.to_numpy().flatten()
and you can also add .tolist() if you want the result to be a Python list.
Edit
In previous versions of Pandas, the values attributed was used instead of the .to_n... | stackoverflow.com |
**Rearrange columns of numpy 2D array**
**Top answer**
This is possible in O(n) time and O(n) space using fancy indexing:
>>> import numpy as np
>>> a = np.array([[10, 20, 30, 40, 50],
... [ 6, 7, 8, 9, 10]])
>>> permutation = [0, 4, 1, 3, 2]
>>> idx = np.empty_like(permutation)
>>> idx[permutation] = np.arange(len... | stackoverflow.com |
**How to prevent TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?**
**Top answer**
The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].
This ... | stackoverflow.com |
**Easy way to test if each element in an numpy array lies between two values?**
**Top answer**
One solution would be:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
(a > 1) & (a < 5) # 1 < element < 5?
# array([False, True, True, True, False]) | stackoverflow.com |
**What is the difference between np.linspace and np.arange?**
**Top answer**
np.linspace allows you to define how many values you get including the specified min and max value. It infers the stepsize:
>>> np.linspace(0,1,11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
np.arange allows you to define... | stackoverflow.com |
**Most efficient way to forward-fill NaN values in numpy array**
**Top answer**
Here's one approach -
mask = np.isnan(arr)
idx = np.where(~mask,np.arange(mask.shape[1]),0)
np.maximum.accumulate(idx,axis=1, out=idx)
out = arr[np.arange(idx.shape[0])[:,None], idx]
If you don't want to create another array and just fil... | stackoverflow.com |
**built-in range or numpy.arange: which is more efficient?**
**Top answer**
For large arrays, a vectorised numpy operation is the fastest. If you must loop, prefer xrange/range and avoid using np.arange.
In numpy you should use combinations of vectorized calculations, ufuncs and indexing to solve your problems as it r... | stackoverflow.com |
**Interpolate NaN values in a numpy array**
**Top answer**
Lets define first a simple helper function in order to make it more straightforward to handle indices and logical indices of NaNs:
import numpy as np
def nan_helper(y):
"""Helper to handle indices and logical indices of NaNs.
Input:
- y, 1d n... | stackoverflow.com |
**Calculating Covariance with Python and Numpy**
**Top answer**
When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).
The 2x2 array returned by np.cov(a,b) has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov is the function you defined above.) | stackoverflow.com |
**Does matplotlib have a function for drawing diagonal lines in axis coordinates?**
**Top answer**
Drawing a diagonal from the lower left to the upper right corners of your plot would be accomplished by the following
ax.plot([0, 1], [0, 1], transform=ax.transAxes)
Using transform=ax.transAxes, the supplied x and y coo... | stackoverflow.com |
**Scikit Learn SVC decision_function and predict**
**Top answer**
I don't fully understand your code, but let's go through the example in the documentation page you referenced:
import numpy as np
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
y = np.array([1, 1, 2, 2])
from sklearn.svm import SVC
clf = SVC()
clf.f... | stackoverflow.com |
**Numpy shuffle multidimensional array by row only, keep column order unchanged**
**Top answer**
You can use numpy.random.shuffle().
This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but their
contents remains the same.
In [2]: import numpy as... | stackoverflow.com |
**Use a.any() or a.all()**
**Top answer**
If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:
>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)
So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the con... | stackoverflow.com |
**Elegant way to perform tuple arithmetic**
**Top answer**
If you're looking for fast, you can use numpy:
>>> import numpy
>>> numpy.subtract((10, 10), (4, 4))
array([6, 6])
and if you want to keep it in a tuple:
>>> tuple(numpy.subtract((10, 10), (4, 4)))
(6, 6) | stackoverflow.com |
**Matplotlib log scale tick label number formatting**
**Top answer**
Sure, just change the formatter.
For example, if we have this plot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.axis([1, 10000, 1, 100000])
ax.loglog()
plt.show()
You could set the tick labels manually, but then the tick locations... | stackoverflow.com |
**Numpy minimum in (row, column) format**
**Top answer**
Use unravel_index:
numpy.unravel_index(A.argmin(), A.shape) | stackoverflow.com |
**Performant cartesian product (CROSS JOIN) with pandas**
**Top answer**
Let's start by establishing a benchmark. The easiest method for solving this is using a temporary "key" column:
pandas <= 1.1.X
def cartesian_product_basic(left, right):
return (
left.assign(key=1).merge(right.assign(key=1), on='key').... | stackoverflow.com |
**Are numpy arrays passed by reference?**
**Top answer**
In Python, all variable names are references to values.
When Python evaluates an assignment, the right-hand side is evaluated before the left-hand side. arr - 3 creates a new array; it does not modify arr in-place.
arr = arr - 3 makes the local variable arr refe... | stackoverflow.com |
**How to convert a python numpy array to an RGB image with Opencv 2.4?**
**Top answer**
You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray.
The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you... | stackoverflow.com |
**ImportError: DLL load failed: The specified module could not be found**
**Top answer**
I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fix... | stackoverflow.com |
**Why is numpy's einsum faster than numpy's built in functions?**
**Top answer**
First off, there's been a lot of past discussion about this on the numpy list. For example, see:
https://mail.python.org/archives/list/numpy-discussion@python.org/thread/MYB7HYCIZIQSFYIUEJU33RBESP5GNJPP/#MYB7HYCIZIQSFYIUEJU33RBES... | stackoverflow.com |
**Python: find position of element in array**
**Top answer**
Have you thought about using Python list's .index(value) method? It return the index in the list of where the first instance of the value passed in is found. | stackoverflow.com |
**How can I "zip sort" parallel numpy arrays?**
**Top answer**
b[a.argsort()] should do the trick.
Here's how it works. First you need to find a permutation that sorts a. argsort is a method that computes this:
>>> a = numpy.array([2, 3, 1])
>>> p = a.argsort()
>>> p
[2, 0, 1]
You can easily check that this... | stackoverflow.com |
**Specifying targets for intersphinx links to numpy, scipy, and matplotlib**
**Top answer**
Where can I find instructions on how to specify targets for :ref:s and :term:s in numpy, scipy, and matplotlib?
I have a Gist with a handful of intersphinx mappings, which now includes all of numpy, scipy and matplotlib. You ... | stackoverflow.com |
**Create a two-dimensional array with two one-dimensional arrays**
**Top answer**
If you wish to combine two 10 element one-dimensional arrays into a two-dimensional array, np.vstack((tp, fp)).T will do it.
np.vstack((tp, fp)) will return an array of shape (2, 10), and the T attribute returns the transposed array with... | stackoverflow.com |
**Remove duplicate rows of a numpy array**
**Top answer**
You can use numpy unique. Since you want the unique rows, we need to put them into tuples:
import numpy as np
data = np.array([[1,8,3,3,4],
[1,8,9,9,4],
[1,8,3,3,4]])
just applying np.unique to the data array will result in t... | stackoverflow.com |
**only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices**
**Top answer**
I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then... | stackoverflow.com |
**array.array versus numpy.array**
**Top answer**
It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the array module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provi... | stackoverflow.com |
**Stratified Sampling in Pandas**
**Top answer**
Use min when passing the number to sample. Consider the dataframe df
df = pd.DataFrame(dict(
A=[1, 1, 1, 2, 2, 2, 2, 3, 4, 4],
B=range(10)
))
df.groupby('A', group_keys=False).apply(lambda x: x.sample(min(len(x), 2)))
A B
1 1 1
2 1 2
3 2 ... | stackoverflow.com |
**Suppressing scientific notation in pandas?**
**Top answer**
quick temporary: df.round(4)
global: pd.options.display.float_format = '{:20,.2f}'.format
The :20 means the total width should be twenty characters, padded with whitespace on the left if it would otherwise be shorter. You can use simply '{:,.2f}' if you don... | stackoverflow.com |
**How do I tell if a column in a pandas dataframe is of type datetime? How do I tell if a column is numerical?**
**Top answer**
I just encountered this issue and found that @charlie-haley's answer isn't quite general enough for my use case. In particular np.datetime64 doesn't seem to match datetime64[ns, UTC].
df['dat... | stackoverflow.com |
**Optimal way to compute pairwise mutual information using numpy**
**Top answer**
I can't suggest a faster calculation for the outer loop over the n*(n-1)/2
vectors, but your implementation of calc_MI(x, y, bins) can be simplified
if you can use scipy version 0.13 or scikit-learn.
In scipy 0.13, the lambda_ argument w... | stackoverflow.com |
**'list' object has no attribute 'shape'**
**Top answer**
Use numpy.array to use shape attribute.
>>> import numpy as np
>>> X = np.array([
... [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
... [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
... [[-5.127249956130981... | stackoverflow.com |
**Initialise numpy array of unknown length**
**Top answer**
Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).
a = []
for x in y:
a.append(x)
a = np.array(a) | stackoverflow.com |
**numpy array TypeError: only integer scalar arrays can be converted to a scalar index**
**Top answer**
I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.
The fix was to simply t... | stackoverflow.com |
**Importing the numpy c-extensions failed**
**Top answer**
Try to uninstall numpy and setuptools first:
pip uninstall -y numpy
pip uninstall -y setuptools
pip install setuptools
pip install numpy
Borrowed from solution provided by mehdiHadji here- https://github.com/ipython/ipyparallel/issues/349 | stackoverflow.com |
**How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?**
**Top answer**
By default, np.genfromtxt uses dtype=float: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask np.genfromtxt to try to guess the actual type of you... | stackoverflow.com |
**ImportError: cannot import name '_validate_lengths'**
**Top answer**
I updated my skimage package.
pip install --upgrade scikit-image
And the problem was solved. It's a problem of version of Skimage, which is solved in 0.14.2. PLus, this version is quite stable.
Installing collected packages: dask, sci... | stackoverflow.com |
**Generating movie from python without saving individual frames to files**
**Top answer**
This functionality is now (at least as of 1.2.0, maybe 1.1) baked into matplotlib via the MovieWriter class and it's sub-classes in the animation module. You also need to install ffmpeg in advance.
import matplotlib.animation as ... | stackoverflow.com |
**pd.NA vs np.nan for pandas**
**Top answer**
As of now (release of pandas-1.0.0) I would really recommend to use it carefully.
First, it's still an experimental feature:
Experimental: the behaviour of pd.NA can still change without warning.
Second, the behaviour differs from np.nan:
Compared to np.nan, pd.NA behav... | stackoverflow.com |
**What is the difference between numpy.fft and scipy.fftpack?**
**Top answer**
SciPy does more:
http://docs.scipy.org/doc/numpy/reference/routines.fft.html
http://docs.scipy.org/doc/scipy/reference/fftpack.html#
In addition, SciPy exports some of the NumPy features through its own interface, for example if you execu... | stackoverflow.com |
**What's an efficient way to find if a point lies in the convex hull of a point cloud?**
**Top answer**
Here is an easy solution that requires only scipy:
def in_hull(p, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is eithe... | stackoverflow.com |
**python numpy/scipy curve fitting**
**Top answer**
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and... | stackoverflow.com |
**Pandas Timedelta in Days**
**Top answer**
Using the Pandas type Timedelta available since v0.15.0 you also can do:
In[1]: import pandas as pd
In[2]: df = pd.DataFrame([ pd.Timestamp('20150111'),
pd.Timestamp('20150301') ], columns=['date'])
In[3]: df['today'] = pd.Timestamp('20150315')
In... | stackoverflow.com |
**Conditionally fill column values based on another columns value in pandas**
**Top answer**
You probably want to do
df['Normalized'] = np.where(df['Currency'] == '$', df['Budget'] * 0.78125, df['Budget']) | stackoverflow.com |
**Python JSON encoder convert NaNs to null instead**
**Top answer**
This seems to achieve my objective:
import simplejson
>>> simplejson.dumps(d, ignore_nan=True)
Out[3]: '{"a": 1, "c": 3, "b": 2, "e": null, "f": [1, null, 3]}' | stackoverflow.com |
**Store numpy.array in cells of a Pandas.DataFrame**
**Top answer**
Use a wrapper around the numpy array i.e. pass the numpy array as list
a = np.array([5, 6, 7, 8])
df = pd.DataFrame({"a": [a]})
Output:
a
0 [5, 6, 7, 8]
Or you can use apply(np.array) by creating the tuples i.e. if you have a datafr... | stackoverflow.com |
**Tensorflow: How do I convert a EagerTensor into a numpy array?**
**Top answer**
There is a .numpy() function which you can use, alternatively you could also do numpy.array(y). For example:
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
x = tf.constant([1., 2.])
print(type(x)) # <... | stackoverflow.com |
**How to create a numpy array of lists?**
**Top answer**
As you discovered, np.array tries to create a 2d array when given something like
A = np.array([[1,2],[3,4]],dtype=object)
You have apply some tricks to get around this default behavior.
One is to make the sublists variable in length. It can't make a 2d array f... | stackoverflow.com |
**Numpy "where" with multiple conditions**
**Top answer**
Try this:
Using the setup from @Maxu
col = 'consumption_energy'
conditions = [ df2[col] >= 400, (df2[col] < 400) & (df2[col]> 200), df2[col] <= 200 ]
choices = [ "high", 'medium', 'low' ]
df2["energy_class"] = np.select(conditions, c... | stackoverflow.com |
**How to plot empirical CDF (ECDF)**
**Top answer**
If you like linspace and prefer one-liners, you can do:
plt.plot(np.sort(a), np.linspace(0, 1, len(a), endpoint=False))
Given my tastes, I almost always do:
# a is the data array
x = np.sort(a)
y = np.arange(len(x))/float(len(x))
plt.plot(x, y)
Which works for me e... | stackoverflow.com |
**Matplotlib Plot Lines with Colors Through Colormap**
**Top answer**
The Matplotlib colormaps accept an argument (0..1, scalar or array) which you use to get colors from a colormap. For example:
col = pl.cm.jet([0.25,0.75])
Gives you an array with (two) RGBA colors:
array([[ 0. , 0.50392157, 1. , 1. ],
[ 1. ... | stackoverflow.com |
**Zero pad numpy array**
**Top answer**
numpy.pad with constant mode does what you need, where we can pass a tuple as second argument to tell how many zeros to pad on each size, a (2, 3) for instance will pad 2 zeros on the left side and 3 zeros on the right side:
Given A as:
A = np.array([1,2,3,4,5])
np.pad(A, (2, 3... | stackoverflow.com |
**How to add items into a numpy array**
**Top answer**
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python lis... | stackoverflow.com |
**check how many elements are equal in two numpy arrays python**
**Top answer**
Using numpy.sum:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([1, 2, 4, 3])
>>> np.sum(a == b)
2
>>> (a == b).sum()
2 | stackoverflow.com |
**How can I solve error "module 'numpy' has no attribute 'float'" in Python?**
**Top answer**
The answer is already provided in the comments by @mattdmo and @tdelaney:
NumPy 1.20 (release notes) deprecated numpy.float, numpy.int, and similar aliases, causing them to issue a deprecation warni... | stackoverflow.com |
**Slice 2d array into smaller 2d arrays**
**Top answer**
There was another question a couple of months ago which clued me in to the idea of using reshape and swapaxes. The h//nrows makes sense since this keeps the first block's rows together. It also makes sense that you'll need nrows and ncols to be part of the shape... | stackoverflow.com |
**list memory usage in ipython and jupyter**
**Top answer**
Assuming that you are using ipython or jupyter, you will need to do a little bit of work to get a list all of the objects you have defined. That means taking everything available in globals() and filtering out objects that are modules, builtins, ipython objec... | stackoverflow.com |
**Convert ndarray from float64 to integer**
**Top answer**
Use .astype.
>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1., 2., 3., 4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])
See the documentation for more options. | stackoverflow.com |
**Python "TypeError: unhashable type: 'slice'" for encoding categorical data**
**Top answer**
X is a dataframe and can't be accessed via slice terminology like X[:, 3]. You must access via iloc or X.values. However, the way you constructed X made it a copy... so. I'd use values
# Importing the librar... | stackoverflow.com |
**Swapping columns in a numpy array?**
**Top answer**
There are two issues here. The first is that the data you pass to your function apparently isn't a two-dimensional NumPy array -- at least this is what the error message says.
The second issue is that the code does not do what you expect:
my_array = numpy.arange(9)... | stackoverflow.com |
**Swapping the dimensions of a numpy array**
**Top answer**
The canonical way of doing this in numpy would be to use np.transpose's optional permutation argument. In your case, to go from ijkl to klij, the permutation is (2, 3, 0, 1), e.g.:
In [16]: a = np.empty((2, 3, 4, 5))
In [17]: b = np.transpose(a, (2, 3, 0, 1)... | stackoverflow.com |
**"synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'." problem in TensorFlow**
**Top answer**
If you're using TF 2.0 a quick solution would be to downgrade your numpy to 1.16.4. (I used 1.17 and received the same warning messages).
1. pip... | stackoverflow.com |
**Numpy extract submatrix**
**Top answer**
Give np.ix_ a try:
Y[np.ix_([0,3],[0,3])]
This returns your desired result:
In [25]: Y = np.arange(16).reshape(4,4)
In [26]: Y[np.ix_([0,3],[0,3])]
Out[26]:
array([[ 0, 3],
[12, 15]]) | stackoverflow.com |
**How to understand numpy strides for layman?**
**Top answer**
The actual data of a numpy array is stored in a homogeneous and contiguous block of memory called data buffer. For more information see NumPy internals.
Using the (default) row-major order, a 2D array looks like this:
To map the indices i,j,k,... of a mul... | stackoverflow.com |
**Fastest way to compute entropy in Python**
**Top answer**
@Sanjeet Gupta answer is good but could be condensed. This question is specifically asking about the "Fastest" way but I only see times on one answer so I'll post a comparison of using scipy and numpy to the original poster's entropy2 answer with slight alter... | stackoverflow.com |
**pandas.read_csv from string or package data**
**Top answer**
To pass a string to pandas read_csv(), you can use io.StringIO, e.g.:
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO("csv string")) | stackoverflow.com |
**Python Pandas - Missing required dependencies ['numpy'] 1**
**Top answer**
I had this same issue immediately after upgrading pandas to 0.19.2. I fixed it with the following install/uninstall sequence from the windows cmd line:
pip uninstall pandas -y
pip uninstall numpy -y
pip install pandas
pip install nump... | stackoverflow.com |
**How to rearrange array based upon index array**
**Top answer**
You can simply use your "index" list directly, as, well, an index array:
>>> arr = np.array([10, 20, 30, 40, 50])
>>> idx = [1, 0, 3, 4, 2]
>>> arr[idx]
array([20, 10, 40, 50, 30])
It tends to be much faster if idx is already an ndarray and not a list, ... | stackoverflow.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.