Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3:如何选择我想要的列,并在缺少列时避免keyerror_Python_Python 3.x_Machine Learning_Categorical Data_One Hot Encoding - Fatal编程技术网

Python3:如何选择我想要的列,并在缺少列时避免keyerror

Python3:如何选择我想要的列,并在缺少列时避免keyerror,python,python-3.x,machine-learning,categorical-data,one-hot-encoding,Python,Python 3.x,Machine Learning,Categorical Data,One Hot Encoding,我有一些明确的价值观 E.g. things = 'cat', dog', 'pen', 'bar' 我通过OneHotEncoding将其编码为数值: car dog pen bar 1 1 1 1 我想使用数据集中的一些列 例如,汽车狗围栏和非酒吧 我通过定义特定列来实现: dataset = dataset[['car', 'dog', 'pen']] 但有时我想要的一些列在我的数据集中不存在,例如“car” 然后Python打印错误: KeyError: "[

我有一些明确的价值观

E.g. things = 'cat', dog', 'pen', 'bar'
我通过OneHotEncoding将其编码为数值:

car dog pen bar
1   1   1   1
我想使用数据集中的一些列

例如,汽车狗围栏和非酒吧

我通过定义特定列来实现:

dataset = dataset[['car', 'dog', 'pen']]
但有时我想要的一些列在我的数据集中不存在,例如“car”

然后Python打印错误:

KeyError: "['car'] not in index"
我如何解决这个问题:

  • 有我想要的专栏
  • 如果缺少所需的列,则避免出现错误
  • 您可以使用以下命令
    dataset.iloc[:,dataset.columns!=“bar”]

    您可以执行一些健全性检查。以下函数就是一个示例:

    def custom_dataset(dataset, req_cols):
        in_, out_ = [], []
        if isinstance(dataset, pd.DataFrame):  # optional
            for col in req_cols:  # check for every existing column
                if col in dataset.columns:
                    in_.append(col)  # append those that are in (i.e. valid)
                else:
                    out_.append(col)  # append those that are NOT in (i.e. invalid)
        return dataset[in_] if in_ else None, out_ if out_ else None
    
    如您所见,它返回两个元素的元组:

  • 数据集只需要现有列,否则返回None(因此可以在结果中检查None以避免错误)
  • 未找到列的列表(用于记录)。否则,如果找到all,则返回None

  • 即使数据集不是
    DataFrame
    的实例,或者用户没有提供任何要收集的列,该函数也不会抛出错误,而是返回
    (无,无)

    如果您提到“数据集”,似乎您指的是熊猫。是这样吗?你能展示一下你最初是如何创建数据集的,这样你的问题就可以重现了吗?Akshat2249,非常感谢。事实上,我不想使用很多列。定义我不想使用的列比定义我想使用的列更难。此外,我不想使用的列也可以是缺席和不缺席。这取决于数据集的大小。Yahya,非常感谢您提供的强大功能。这正是我所需要的。很高兴我能帮上忙:)Yahya,基于您的函数I 1)创建数据集中所需列的列表2)使用此列表进行选择:[col for col in col_calc if col in df.columns]