我正在处理不完整的数据,这些数据围绕具有不同数据结构的文件进行分割。所以我写了一个带有np的脚本。在哪里检查键是否在列名中,是否在df中写入键。我用的是带np的熊猫。where并引发KeyError。例子:
df['col_result'] = np.where('col1' in df.columns, df['col1'], 'None')
KeyError Traceback (most recent call last)
~anaconda3libsite-packagespandascoreindexesbase.py in get_loc(self, key, method, tolerance)
2894 try:
-> 2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'col1'
由于您正在测试col1
是否在df
的列中,看起来col1
可能在列中不可用。对于这种情况,当您在代码中编码df['col1']
时,它将为col1
引发KeyError
。
当您想要将整个列分配给新列时,使用np.where()
(主要用于到达行可以满足或不满足条件时)不会获得太多好处。因此,可以考虑将代码更改为简单的if-else语句,如下所示:
if 'col1' in df.columns:
df['col_result'] = df['col1']
else:
df['col_result'] = 'None'