【发布时间】:2022-01-04 12:00:15
【问题描述】:
我创建了一个 2 行 5 列的 2d numpy 数组。
import numpy as np
import pandas as pd
arr = np.zeros((2, 5))
arr[0] = [12, 94, 4, 4, 2]
arr[1] = [1, 3, 4, 12, 46]
我还创建了一个包含两列 col1 和 col2 的数据框
list1 = [1,2,3,4,5]
list2 = [2,3,4,5,6]
df = pd.DataFrame({'col1': list1, 'col2': list2})
我使用 pandas 的 isin 函数与 col1 和 col2 创建一个布尔值列表,如下所示:
df['col1'].isin(df['col2'])
输出
0 False
1 True
2 True
3 True
4 True
现在我想使用这些 bool 值对我之前创建的二维数组进行切片,我可以对单行执行此操作,但现在一次对整个二维数组进行切片:
print(arr[0][df['col1'].isin(df['col2'])])
print(arr[1][df['col1'].isin(df['col2'])])
输出:
[94. 4. 4. 2.]
[ 3. 4. 12. 46.]
但是当我做这样的事情时:
print(arr[df['col1'].isin(df['col2'])])
但这给出了错误:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 2 but corresponding boolean dimension is 5
有没有办法做到这一点?
【问题讨论】:
-
arr[:, df['col1'].isin(df['col2'])]?这首先通过:选择所有行,然后您的布尔系列作用于要选择的列。