Find function with numpy - python-3.x

I have a numpy array and I want to find all the indexes that verifies a certain condition. Example, I want to plot the Heaviside function;
import numpy as np
x=np.linspace(-5,5,11)
k_neg=x.find(x<0)
k_pos=x.find(x>=0)
y=np.zeros(len(x))
y(k_neg)=-1
y(k_pos)=1
I don't find such a function (like it exists on Matlab).
Note : my actual problem IS NOT to plot Heavyside, of corse ;)

As said by Paul Panzer;
Sounds like you are looking for np.where
Which solved my problem.

I would do it in one line with numpy:
import numpy as np
x = np.linspace(-5,5,11)
y = ((x>=0)*2)-1

Related

How to create a variable number of dimensions for mgrid

I would like to create a meshgrid of variable dimensions by specifying the dimensions with a variable i.e. specifying dim=2, rather than manually changing the expression as in the example below to set a 2D mesh grid.
How would I implement a wrapper function for this?
The problem stems from not being familiar with the syntax that mgrid uses (index_tricks).
import numpy as np
mgrid = np.mgrid[
-5:5:5j,
-5:5:5j,
]
Observed documentation for mgrid, but there seems to be no info on setting the number of dimensions with a variable.
You can create a tuple containing the slice manually, and repeat it some number of times:
import numpy as np
num_dims = 2
mgrid = np.mgrid[(slice(-5, 5, 5j),) * num_dims]

Scipy.detrend: Function changes range of values

I am trying to detrend this one dimensional array:
array([13.64352283, 13.48914862, 13.00767009, 13.35416524, 13.60143818,
13.40895156, 13.48349417, 13.65703125, 13.4959721 , 13.28891263,
12.97999066, 13.01112397, 12.79519705, 13.32030445, 13.19949068,
12.88691975, 13.32079707])
The function runs without errors but changes the range of values from ~[12,14] to ~[-0.4,0.4].
I believe it is due to the small std dev of the values that this happens.
Any ideas how to fix this, so I can plot the array with trend and the detrended one into one plot?
Normalization is not an option.
Please help.
Well, that is exactly what detrend does: it subtracts the values of the least square linear approximation to the input.
Here is a plot to illustrate what happens:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
y = np.array([13.64352283, 13.48914862, 13.00767009, 13.35416524, 13.60143818,
13.40895156, 13.48349417, 13.65703125, 13.4959721, 13.28891263,
12.97999066, 13.01112397, 12.79519705, 13.32030445, 13.19949068,
12.88691975, 13.32079707])
plt.plot(y, color='dodgerblue')
plt.plot(signal.detrend(y), color='limegreen')
plt.plot(y - signal.detrend(y), color='crimson')
plt.show()
The red line in the plot is the linear approximation that got subtracted from the original data to obtain detrend(y).

Create a square matrix in python

I want to get an number from user an create a square matrix of number*number but I can't do it for now. Could you please help me about it. It should look like this:
https://i.stack.imgur.com/ZxtCl.png
import numpy as np
input = 4
matrix = np.array(range(0, input**2 - 1)).reshape((input, input))

Python equivalent of Pulse Integration (pulsint) MATLAB function?

I am surfing online to find Python equivalent of function pulsint of MATLAB , and till now I haven't found anything significantly close to it.
Any heads up in this regards will be really helpful!
You can easily create your own pulsint function.
The pulsint formula:
You need the numpy library to keep the things simple
import numpy as np
import matplotlib as mpl
# Non coherent integration
def pulsint(x):
return np.sqrt(np.sum(np.power(np.absolute(x),2),0))
npulse = 10;
# Random data (100x10 vector)
x = np.matlib.repmat(np.sin(2*np.pi*np.arange(0,100)/100),npulse,1)+0.1*np.random.randn(npulse,100)
# Plot the result
mpl.pyplot.plot(pulsint(x))
mpl.pyplot.ylabel('Magnitude')

Robust statistics linear regression in seaborn pairplot

Trying to implement robust statistics instead of ordinary least squares (OLS) fitting so that outliers aren't such a problem to my fits.
I was hoping to implement this in the pairplot function of seaborn and can't see and easy way to add this from the AP documentation as there doesn't seem to be a key word argument for the fit.
From: scipy lectures They suggest using the following but I guess thats for regplot where you can define the fit using
`fit = statsmodels.formula.api.rlm()`
Here is some sample code
import seaborn as sns; sns.set(style="ticks", color_codes=True)
import matplotlib.pyplot as plt
%matplotlib inline
iris = sns.load_dataset("iris")
sns.pairplot(iris, kind="reg")#, robust = True)
plt.show()
Thanks in advance!
Edit: I found a workaround, but loose the 'hue' function apparently that could be done on the pairplot. Would be a nice feature to add robust option to pairplot.
Code:
def corrfunc(x, y, **kws):
r, _ = stats.pearsonr(x, y)
ax = plt.gca()
ax.annotate("r = {:.2f}".format(r), xy=(.1, .9), xycoords=ax.transAxes)
g = sns.PairGrid(df1, palette=["red"])
g.map_upper(sns.regplot, robust = True)
g.map_diag(sns.distplot, kde=True)
g.map_lower(sns.kdeplot, cmap="Blues_d")
g.map_lower(corrfunc)
Extra keywords, such as "robust = True" can be passed to regplot via the plot_kws argument:
sns.pairplot(df1,kind='reg',hue='species',plot_kws=dict(robust=True,n_boot=50))
NB: In this example I have also decreased n_boot to reduce the runtime (see "robust" in regplot documentation), so the confidence intervals might be incorrect).

Resources