【问题标题】:how to use pandas isin function in 2d numpy array?如何在二维 numpy 数组中使用 pandas isin 函数?
【发布时间】: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]

我还创建了一个包含两列 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'])]?这首先通过: 选择所有行,然后您的布尔系列作用于要选择的列。

标签: pandas numpy isin


【解决方案1】:

你应该对数组的第二维进行切片:

arr[:, df['col1'].isin(df['col2'])]

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2019-05-05
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多