2017-09-26 106 views
1

到目前爲止,我正在獲取Python數據框列中特定值的第一個匹配記錄的索引。我得到用下面的代碼它:Python Pandas - 識別Dataframe列中第一個匹配值的索引

df1.loc[df1.Column1 == 'word1'].index.tolist()[0] 

假設如果「WORD1」是在索引位置例如數據幀本四次:3,7,9,14,在上述命令將返回我的回答爲

現在我需要檢查列的多個值相同,輸出應該是任何這些值的第一個匹配索引。

我嘗試了幾個選項,如下所示,但徒勞無功。

df1.loc[df1.Column1 == 'word1'|'word2'].index.tolist()[0] 
df1.loc[df1.Column1 == 'word1','word2'].index.tolist()[0] 
df1.loc[df1.Column1 == 'word1' or 'word2'].index.tolist()[0] 

有關如何檢查多個值的任何想法嗎?

回答

1

你需要isin的條件:

df1.loc[df1.Column1.isin(['word1','word2'])].index.tolist()[0] 

Simplier解決方案與idxmax爲第一最大值獲取指標,因爲True s的處理類似1 S:

print (df1.Column1.isin(['word1','word2'])) 
0 False 
1 False 
2 False 
3  True 
4 False 
5 False 
6  True 
7 False 
Name: Column1, dtype: bool 

df1.Column1.isin(['word1','word2']).idxmax() 

或者與numpy.where

np.where(df1.Column1.isin(['word1','word2']))[0][0] 

樣品:

df1 = pd.DataFrame({ 'Column1':['s','g','h','word2','d','f','word1','d']}) 

a = df1.Column1.isin(['word1','word2']).idxmax() 
print (a) 
3 
+0

非常感謝。但是,你能否提供更多的關於idxmax的信息。通過它的名字,我認爲必須有一種叫做idxmin的東西。 – JKC

+0

是的,'df1.Column1.isin(['word1','word2'])。idxmin()'返回第一個'False'索引,用'df1 = pd.DataFrame({'Column1':['word2 ','g','h','word2','d','f','word1','d']})' – jezrael

+1

明白了:-)謝謝@jezrael – JKC

相關問題