[英]Filter Numpy Array with optional argument
I am building a function which should prepare my data depending on the input.我正在构建一个 function 应该根据输入准备我的数据。 The variable
x_imp
contains indices on which features are important.变量
x_imp
包含对哪些特征很重要的索引。 However sometimes I still need all features so if 'x_imp = None' nothing should happen.但是有时我仍然需要所有功能,所以如果 'x_imp = None' 什么都不会发生。
My solution was this (this is not the whole function just the inputs):我的解决方案是这样的(这不是整个 function 只是输入):
def get_train_data(x_cat, x_num,x_imp = None):
x_cat = x_cat[:,x_imp]
x_num = x_num[:,x_imp]
return x_train
But this changes the shape of the data.但这会改变数据的形状。 For example if
data.shape = (4, 5)
then data[:,None].shape = (4, 1, 5)
例如,如果
data.shape = (4, 5)
那么data[:,None].shape = (4, 1, 5)
How do I avoid this problem?我该如何避免这个问题?
This happens because slicing by None
is an alias for np.newaxis
.发生这种情况是因为
None
切片是np.newaxis
的别名。 Is there a reason not to just add an explicit if
statement?是否有理由不只添加显式
if
语句?
def get_train_data(x_cat, x_num,x_imp = None):
if x_imp is not None:
x_cat = x_cat[:,x_imp]
x_num = x_num[:,x_imp]
return x_train
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.