Python:如果值不等于零,则仅对数组进行幂运算



我有下面的函数,在其中我运行了几个回归。一些估计的系数被输出为"0",自然地,当它们被指数化时,它们会变成"1"。

理想情况下,在估计系数为零的情况下,我会让sm.OLS()输出"空白",而不是"零"。但我试过了,但这似乎不可能。

所以,或者,我更喜欢保留零而不是1。这将不需要对这行代码中的零进行幂运算:exp_coefficients=np.exp(results.params)

我怎么能这么做?

import statsmodels.api as sm
df_index = []
coef_mtr = [] # start with an empty list
for x in df_main.project_x.unique():

df_holder=df_main[df_main.project_x == x]
X = df_holder.drop(['unneeded1', 'unneeded2','unneeded3'], axis=1)
X['constant']=1 
Y = df_holder['sales']
eq=sm.OLS(y, X)
results=eq.fit()
exp_coefficients=np.exp(results.params)
#   print(exp_coefficients)
coef_mtr.append(exp_coefficients)
df_index.append(x)
coef_mtr = np.array(coef_mtr)
# create a dataframe with this data
df_columns = [f'coef_{n}' for n in range(coef_mtr.shape[1])]
df_matrix=pd.DataFrame(data = coef_mtr, index = df_index, columns = df_columns)

最干净的可能是使用中的where关键字(而不是函数(

out = np.exp(in_,where=in_!=0)

这将跳过所有零值。但因为当我说跳过时,我的意思是跳过,这将使相应的值未初始化。因此,我们需要将它们预设为零:

out = np.zeros_like(in_)
np.exp(in_,where=in_!=0,out=out)

最新更新