python - 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)
推荐阅读
- wix3.11 - 使用自定义操作编译基于 Wix 工具集的安装项目时出错
- microsoft-teams - 有没有办法以编程方式访问 Teams 群聊视图中的“不在办公室”状态区域?
- angular-material - 根据内容大小将滚动条添加到 mat 选项卡
- c++ - 动画 gif 图像在我的无模式 Gtk::Dialog 中没有动画
- android - Nativescript 文件夹文件在哪里
- sql - SQL:对嵌套查询使用 AND 语句
- javascript - 来自 express 的 MongoDB API
- postgresql - Postgres 将一个过程的 refcursor 输出传递给另一个过程
- html - 如何定位用户位置:css中的粘性
- flutter - Flutter/Dart 变量丢失/尝试从不同类获取时不断重新初始化