簡體   English   中英

在python中使用布爾邏輯隔離熊貓列

[英]Isolating pandas columns using boolean logic in python

我正在嘗試獲取滿足以下布爾語句之一或全部的數據框的行:

1) df['colName'] == 0
2) df['colName'] == 1

我已經嘗試過這些,但是沒有一個可行(拋出錯誤):

df = df[df['colName']==0 or df['colName']==1]
df = df[df['colName']==0 | df['colName']==1]

還有其他想法嗎?

您失蹤了()

df = df[(df['colName']==0) | (df['colName']==1)]

這可能會引發復制警告,但仍然可以使用。

如果您不想復制警告,請使用具有以下內容的索引器:

indexer = df[(df['colName']==0) | (df['colName']==1)].index
df = df.loc[indexer,:]

您可以使用eq代替==來清理已完成的操作

df[df.colName.eq(0) | df.colName.eq(1)]

對於這種情況,我建議使用isin

df[df.colName.isin([0, 1])]

使用query也可以,但是速度較慢

df.query('colName in [0, 1]')

定時
在下面定義的df上, isin最快
df = pd.DataFrame(np.random.randint(3, size=10000), columns=['colName'])

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM