首页 > 解决方案 > 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)

标签: pythonpandasnumpystatsmodels

解决方案


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

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

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

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

推荐阅读