115,289 questions
-1
votes
1
answer
54
views
How to randomly select a pixel within a kernel and attribute its value to the center pixel? [closed]
In order to investigate whether the decisions of a CNN for image classification are predominantly driven by image regions related to relatively fine object features, I am looking for an image ...
4
votes
1
answer
72
views
Efficiently coercing a Python list to a Numpy array with a custom datatype
I am using python to build an OpenGL rendering engine and am using numpy arrays with a custom datatype to store my vertex data.
import numpy as np
data_type_vertex = np.dtype({
"names": ...
0
votes
0
answers
46
views
Why I'm getting blank nullcline plot?
I'm trying to plot nullclines for a nonlinear system and determine fixed points from the same. However till now my code is not good enough to generate the plots. Presently I'm only able to get a blank ...
1
vote
1
answer
51
views
What is the correct NumPy representation of a row vector for gradients
I am doing an assignment on matrices and gradients, where the final answer must be expressed as a row vector.
vr = np.array([1, 2, 3])
vrr = np.array([[1, 2, 3]])
Mathematically, a row vector should ...
Advice
2
votes
5
replies
78
views
Numpy handling small imaginary parts differently
There is a difference in behaviour on macOS with arm64 CPU vs other Linux with amd64.
For numpy v1 on arm64, it seems there is an internal logic guaranteeing the imaginary part to be exactly 0:
>&...
2
votes
1
answer
63
views
How do I make a custom field output different datatypes depending on file asking for data?
I'm building a molecule properties displaying website using django and sqlite. The database takes a numpy array and stores it as a BLOB. Currently, it just outputs the numpy array back out when asked ...
0
votes
0
answers
91
views
Noiseless Gaussian Process Regression not crossing the training points
I'm trying to perform a Gaussian Process Regression on series of data points Y and ln(X+(10^-4)) (The X values are used in log scale to create the model)
X ln(X+(10^-4)) Y
0.00001 -9.11503019 ...
2
votes
1
answer
32
views
How do I fix a "TypeError: bad number of pixels" in a healpy.fitsfunc.write_map call?
I have downloaded the HEALPix5 DECaPS 3D dust extinction map (from arXiv:2503.02657) and imported it as a numpy array meanmap. The array gives an expected result (51415400, 1, 120) to the meanmap....
2
votes
1
answer
106
views
numpy 2.2.6 tries to build on Windows 11 x64 instead of using wheel
originally I was trying to install opencv-python which fails on trying to install numpy:2.2.6
So I am trying to just install this numpy and for some obscure reason it tries to build it! instead of ...
3
votes
3
answers
107
views
Numerically finding the minimum value of a variable where a function equals a value
I have a black box function baseball that determines the magnitude of the distance that a baseball travels when launched. It takes the initial speed, the angle of launch and the initial spin. Assuming ...
1
vote
1
answer
91
views
Scipy Hessian with Numpy cross product
I need to compute the Hessian of a function involving cross products in Python. As an experiment, I consider the simple function
def func(x):
return np.sum(np.cross(x[0:3], x[3:6]))
and compute the ...
1
vote
0
answers
66
views
PSTH with numpy.histogram shows periodic “gaps” at bin boundaries even after integer time conversion—how to bin robustly?
I’m computing peristimulus time histograms (PSTHs) in Python. Each trial aligns spikes to a reach-start timestamp and bins them into fixed-width bins. I see vertical “gaps” (low counts) at exact bin ...
0
votes
1
answer
47
views
Creating 3d Mesh from Z stack of ROIs
I have a set of 3D ROI label stacks stored as TIFF files, where each ROI represents a single cell. I want to generate surface meshes(I use trimesh) suitable for downstream shape analysis.
I tried ...
-4
votes
0
answers
59
views
Getting "ERROR: No matching distribution found for numpy" while installing NumPy on Mac
I am trying to install and import numpy on my Mac but in the terminal of Pycharm, it comes up with a error message as shown below.
I am a relatively new coder in python so I am extremely confused.
...
Best practices
1
vote
1
replies
90
views
Applying Cosine Similarity to multiple vectors at once
I am implementing cosine similarity to my vector database using python and numpy. I would like to know if I should loop through every database entry and find the cosine similarity or is there a way of ...
0
votes
1
answer
45
views
Multiple CDFS on the same plot with specified ranges
I was trying to do something for a project where I create two random 3D vectors, project them onto a 2D plane by removing their x-component, taking the dot product between the two to find their ...
Advice
0
votes
4
replies
62
views
Regex-logic in a numpy/torch array
Evening,
Is there any way to find a specific sequence of numerical values, matching certain logic (in the same way as in a regex), within a numpy/torch array or matrix row?
I know i could just convert ...
3
votes
1
answer
84
views
pyQt - Trying to draw B-Spline curve with mouse
I am trying to have a Pen Tool in my pyqt6 application. I am trying to make it how Inkscape's PenTool works. For now, I am trying to achieve the 'B-Spline' mode.
The issue is that my curve does not ...
3
votes
2
answers
134
views
Calculate cumulative value based on another column [duplicate]
Having this kind of pandas dataframe
df = pd.DataFrame({
'ts_diff':[0, 0, 738, 20, 29, 61, 42, 18, 62, 41, 42, 0, 0, 729, 43, 59, 42, 61, 44, 36, 61, 61, 42, 18, 62, 41, 42, 0, 0]
})
ts_diff - is ...
Advice
2
votes
1
replies
72
views
Is there a way to vectorize the De Casteljau's algorithm in NumPy?
De Casteljau's algorithm is used to interpolate a Bézier curve and consists a recursive (or iterative) procedure to reduce the number of linear segments until only one is left and the interpolation ...
2
votes
2
answers
129
views
Deserializing msgpack_numpy array in browser
I make a web app, the server side is running Python and processes data with numpy. I want to display charts from the numpy data on the browser.
On the server I encode a list of numpy arrays with ...
1
vote
1
answer
142
views
How to modify an array for a specific purpose
I am working on some array T and a condition based on the array D:
import numpy as np
T = np.array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8]])
D = np.array([-6, ...
1
vote
0
answers
163
views
Plotting linear regression for geometric intuition
I am regressing Y~(X1, X2) such that this fit is perfect (R squared is 1), where the R squared for Y~X1 and Y~X2 are chosen somewhere in the interval $(0,1)$. I am trying to create the numerical ...
3
votes
2
answers
242
views
BPTK-Py: base ** variable_exponent in equation returns 1.0; np.power/np.log not supported on Converter
I’m building a simulation in BPTK-Py and need a power with a variable exponent inside a node equation:
Resale_Value_DM1.equation = 1 - Depreciation_DM
Resale_Value_DM2.equation = Resale_Value_DM1 ** ...
-5
votes
0
answers
58
views
Upgrade to 3.14 causes np.float64 to print in output--how do I fix? [duplicate]
I recently upgraded to Python 3.14. This caused the below weird output in my dataframe:
Stock Price ATM Theta Return Roll Avg
0 SOFI np.float64(29.68) np....
0
votes
2
answers
85
views
unable to install pytidycensus
I tried to install pytidycensus per these instructions: https://mmann1123.github.io/pytidycensus/index.html
pip install pytidycensus
OS Windows 11, current as of 10/31/2025, with Python 3.13.7 ...
4
votes
3
answers
118
views
numpy vectorise approach to creating array results computed from indices
What is an efficient numpy way of achieving an array of results based on a pair of index datasets?
So, lets say there are 2 arrays these are the row and column headers in the table underneath:
a = [1,...
0
votes
0
answers
100
views
RecursionError in YouCompleteMe for Python Docs in VIm
I am trying to use YouCompleteMe in Vim for getting python documentation (using YcmCompleter GetDoc and the vim pop up menu). This works well for normal python commands, but there seems to be various ...
1
vote
1
answer
75
views
EDL generation with python 3.10 (imagehash & numpy) produces complete nonsense on a greater amount of files
I have a directory of ca. 1600 PNGs (1000x400 res. previews of frames) and want to generate an EDL so I do not have to render the same frame several times.
So far, I have successfully run the ...
3
votes
2
answers
136
views
Expanding np.memmap
I have huge np.memmap objects and need to expand them regularly. I was wondering if my current approach is safe and also the most efficient one and started searching the internet. I stumbled across ...
3
votes
1
answer
144
views
Build numpy 2.3+ without accelerated libraries
Related post: Compile numpy WITHOUT Intel MKL/BLAS/ATLAS/LAPACK
Recent versions of numpy use meson for build configuration, I can build numpy from source but failed to exclude BLAS/LAPACK/... deps.
...
1
vote
0
answers
162
views
What does np.ones_like represent in a quiver plot of a differential equation?
I found some similar questions about quiver plots and direction fields, but I’m still confused about the meaning of these two lines in many examples:
What do dx = np.ones_like(f) and dy = f mean in a ...
2
votes
1
answer
112
views
Does `jax` compilation save runtime memory by recognizing array elements that are duplicated by indexing
Consider the example code:
from functools import partial
from jax import jit
import jax.numpy as jnp
@partial(jit, static_argnums=(0,))
def my_function(n):
idx = jnp.tile(jnp.arange(n, dtype=int)...
0
votes
0
answers
127
views
Convert NETCDF files into TIF files
I’m creating a Python program that converts NetCDF files into GeoTIFFs, allowing the user to select the variable and time step using a Tkinter interface.
The conversion works, but I’m having a ...
1
vote
2
answers
112
views
Why does NumPy load() take longer in a larger script than in another?
I scan for a trigger and when I get it, load a .npy file and process it. It started to take almost 2 seconds to load the NumPy file from within the process but when I tried to load the same file from ...
4
votes
1
answer
96
views
Obtaining cumulative product for a list elements
I tried to calculate the cumulative products for my list elements as below. In my list, each element is two-dimensional list:
import numpy as np
Orig_list = [[[1,2,3], [4,5,6], [7,8,9]], [[11,3,4], [...
1
vote
1
answer
91
views
How to read a chunk of big tiff file in Python? [closed]
I have a TIFF file with a size of (48000, 432000) and I would like to upload only a piece of the image, for example, pass a parameter like (X, Y, wid, hei), where X, Y are the coordinates of the upper-...
0
votes
0
answers
95
views
How to use sklearn imputation methods on numpy.void (record or structured array, I'm not sure) ndarray
Code:
import numpy as np
import sklearn as skl
data = np.genfromtxt("water_potability.csv", delimiter = ",", names = True)
print(data)
print(data.shape)
print(type(data[0]))
...
-4
votes
1
answer
117
views
NumPy high-dimensional array automatically rearranges after subsetting
Today I wanted to use the following command to subset a numpy high-dimensional array, but was surprised to find that the two methods were completely different. I'm very curious why numpy reorders the ...
1
vote
1
answer
112
views
Combining Identically Indexed and Column Dataframes into 3d Dataframe
I have 3 2D DataFrames, all with identical indexes (datetime range) and column names, but different data for these labels. I would like to combine these three 2D dataframes into 1 3D DataFrame with an ...
1
vote
1
answer
96
views
Calculating MultiIndex intersection to a given tolerance in an efficient way
I have two DataFrames, data1 and data2, with 3-level multiindices. The first two levels are floats, and correspond to spatial coordinates (say longitude and latitude). The third level, time, is based ...
2
votes
1
answer
109
views
How to prevent overlapping contours for periodic values in matplotlib
The example code creates a 2D visualization of angles relative to the center. Contour lines with labels are added to show lines of constant angle.
import numpy as np
import matplotlib.pyplot as plt
n ...
5
votes
1
answer
209
views
Divide by zero encountered in matmul on MacOS M4 with numpy v2.0.0
I'm encountering a strange RuntimeWarning: divide by zero encountered in matmul when performing a simple matrix multiplication on my new Apple M4 machine.
The most peculiar part is that this warning ...
4
votes
1
answer
118
views
Numpy vectorising n-variable function by index
Given a closed-form function f(x,y,z), what is the most efficient way to fill up a 3D ndarray arr[z][y][x] with the values of f(x,y,z)?
For example, if I wanted a 3D ndarray arr[z][y][x] with each ...
4
votes
2
answers
209
views
Python multiprocessing shared memory seems to hang or crash when interacting with small numpy arrays
I've been trying to parallelize some code that I wrote in python. The actual work is embarrassingly parallel, but I don't have much experience with multiprocessing in Python.
The actual code I'm ...
2
votes
1
answer
139
views
FFT-based quasi-steady detection issue
I am trying to detect the beginning of a quasi-steady regime in time series data representing drag (Fx) and lift (Fy) forces after an initial transient.
Initially, I used a slope-based method, but it ...
2
votes
1
answer
109
views
Shape of sliced array from shape of array and slice
If I know the shape of a numpy array like (1000, 50), and I have an arbitrary selection expressed as an IndexExpression, let's say np.s_[:200, :], how can I evaluate the shape of the sliced array (in ...
-1
votes
1
answer
122
views
What types are required for numpy.abs()? [closed]
I am trying to make an app in python that takes in equations and outputs them in a graph or solves the equation(s). However in the equation-parsing function, I cannot work out which types are required ...
2
votes
2
answers
119
views
Numpy random normal test shows unexpected results with low p-value
I am performing some tests on the normality of the numpy random generator. Running the following code, the stats.normaltest shows some seeds with low pvalue (which highlights non-normal distribution).
...
0
votes
1
answer
93
views
RuntimeError: Numpy is not available when running Streamlit + PyTorch + Torchvision app on Streamlit Cloud
`I’m deploying a Streamlit app on Streamlit Cloud that uses PyTorch and Torchvision for image segmentation.
Locally, everything works fine, but when I deploy on Streamlit Cloud I get this error:
File &...