我正在尝试 iloc 方法。根据文档, boolean 数组是允许的输入。
我理解这一点的方式是,如果我有一个值为 F、T、T、T 的 boolean 数组 idx,并且我将其作为输入传递,如下所示: df.iloc(: , idx) 那么我将得到第二个、df 的第 3d 和第 4 列(假设 df 有 4 列)。
我尝试实现这个,但遇到了错误。
作为示例,我有一个数据框 df
col1 col2 col3 col4
0 1 2 3 4
1 5 6 7 8
我还有一个 Pandas boolean 系列:
idx = pd.Series(['False', 'True', 'True', 'True'])
我将 boolean 系列转换为 boolean np.array:
idx = idx.values
然后我将其传递给 iloc
df.iloc[: , idx]
我收到错误消息:
IndexError: positional indexers are out-of-bounds
我不明白,因为数据框有 4 列,并且我传递了 4 个 boolean 值。
我们将不胜感激您的帮助。
最佳答案
您的问题是您向 iloc 传递了一系列字符串,而不是一系列 boolean 值。您没有创建 boolean 数组,而是创建了一系列值为“True”和“False”的字符串。
改变这个
idx = pd.Series(['False', 'True', 'True', 'True'])
至此
idx = pd.Series([False, True, True, True])
您还必须使用您创建的系列的值,因为我收到 df.iloc[:, idx]
的 NotImplemented
错误
所以用这个代替:
df.iloc[:, idx.values]
关于python - 使用 boolean 数组调用 iloc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491574/