我創建了一個 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})
我使用 pandasisin函式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
有沒有辦法實作這一目標?
uj5u.com熱心網友回復:
您應該在陣列的第二個維度上切片:
arr[:, df['col1'].isin(df['col2'])]
輸出:
array([[94., 4., 4., 2.],
[ 3., 4., 12., 46.]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403492.html
標籤:
