Python Pandas 獲取列匹配特定值的行的索引問題
給定一個帶有列"BoolCol"的DataFrame,如何找到滿足條件"BoolCol" == True的DataFrame的索引
目前有迭代的方式來做到這一點:
for i in range(100,3000):
if df.iloc[i]['BoolCol']== True:
print i,df.iloc[i]['BoolCol']
這雖然可行,但不是標準的 Pandas 方式。經(jīng)過一番研究,我目前正在使用這個代碼:
df[df['BoolCol'] == True].index.tolist()
這個給了我一個索引列表,但跟我想要的不匹配,當檢查:
df.iloc[i]['BoolCol']
其結(jié)果實際上是False!
如何使用正確的 Pandas 方式做到這一點?
最佳解決方法
df.iloc[i]返回df的第i行。 i不引用索引標簽,i是從0開始的索引。
相反,屬性index返回實際的索引標簽,而不是數(shù)字row-indices:
df.index[df['BoolCol'] == True].tolist()
或者等同地,
df.index[df['BoolCol']].tolist()
通過使用帶有"unusual"索引的DataFrame,可以非常清楚地看到差異:
df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
index=[10,20,30,40,50])
In [53]: df
Out[53]:
BoolCol
10 True
20 False
30 False
40 True
50 True
[5 rows x 1 columns]
In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]
如果你想使用索引,
In [56]: idx = df.index[df['BoolCol']] In [57]: idx Out[57]: Int64Index([10, 40, 50], dtype='int64')
那么您可以使用loc而不是iloc選擇行:
In [58]: df.loc[idx] Out[58]: BoolCol 10 True 40 True 50 True [3 rows x 1 columns]
請注意,loc也可以接受布爾數(shù)組:
In [55]: df.loc[df['BoolCol']] Out[55]: BoolCol 10 True 40 True 50 True [3 rows x 1 columns]
如果您有一個布爾數(shù)組mask,并且需要序數(shù)索引值,則可以使用np.flatnonzero來計算它們:
In [110]: np.flatnonzero(df['BoolCol']) Out[112]: array([0, 3, 4])
使用df.iloc按順序索引選擇行:
In [113]: df.iloc[np.flatnonzero(df['BoolCol'])] Out[113]: BoolCol 10 True 40 True 50 True python pandas

參考文獻
Python Pandas: Get index of rows which column matches certain value
總結(jié)
以上所述是小編給大家介紹的Python Pandas 獲取列匹配特定值的行的索引問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Pytorch微調(diào)BERT實現(xiàn)命名實體識別
命名實體識別(NER)是自然語言處理(NLP)中的一項關(guān)鍵任務(wù),它涉及識別和分類文本中的關(guān)鍵實體,BERT是一種強大的語言表示模型,在各種 NLP 任務(wù)中顯著提高了性能,包括 NER,在本文中,我們將展示如何使用 PyTorch 對預(yù)訓練的 BERT 模型進行微調(diào),以用于 NER 任務(wù)2025-03-03
phpsir 開發(fā) 一個檢測百度關(guān)鍵字網(wǎng)站排名的python 程序
一個檢測百度關(guān)鍵字網(wǎng)站排名的python 程序 phpsir 開發(fā)2009-09-09
Python使用conda如何安裝requirement.txt的擴展包
這篇文章主要介紹了Python使用conda如何安裝requirement.txt的擴展包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

