如何在 2d numpy 数组中使用 pandas isin 函数?

how to use pandas isin function in 2d numpy array?

我创建了一个 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]

我还创建了一个包含两列 col1col2

的数据框
list1 = [1,2,3,4,5]
list2 = [2,3,4,5,6]
df = pd.DataFrame({'col1': list1, 'col2': list2})

我将 pandas isin 函数与 col1col2 一起使用来创建一个布尔值列表,如下所示:

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'])]

输出:

array([[94.,  4.,  4.,  2.],
       [ 3.,  4., 12., 46.]])