到目前为止,我正在获取 Python 数据框列中特定值的第一个匹配记录的索引。我使用下面的代码得到它:
df1.loc[df1.Column1 == 'word1'].index.tolist()[0]
假设如果“word1”在数据框中出现四次,例如在索引位置:3、7、9、14,则上述命令将返回答案为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
用于获取第一个最大值的索引,因为 True
的句柄类似于 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
关于Python Pandas - 识别数据帧列中第一个匹配值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428108/