Python Pandas - 识别 Dataframe 列中第一个匹配值的索引

Python Pandas - Identifying the index of first matching value in a Dataframe column

到目前为止,我正在获取 Python 数据框列中特定值的第一个匹配记录的索引。我使用下面的代码得到它:

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

假设如果 'word1' 在数据框中出现四次,例如在索引位置:3、7、9、14,上述命令将 return 我的答案为 3

现在我需要检查列的多个值是否相同,输出应该是任何这些值的第一个匹配索引。

我尝试了如下所示的几个选项,但没有成功。

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]

知道如何在此处检查多个值吗?

您需要 isin 条件:

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

使用 idxmax 获取第一个最大值的索引的更简单的解决方案,因为 Trues 的句柄类似于 1s:

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