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

标签 python pandas python-3.6

到目前为止,我正在获取 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 的句柄类似于 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

关于Python Pandas - 识别数据帧列中第一个匹配值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428108/

相关文章:

python 从表中选择列,其中列 = self.variable

python - 同一个类中的同名函数 - 有没有一种优雅的方法来确定调用哪个?

python - 当 QThread() 停止运行时(Python),我是否需要手动调用 .quit() 方法?

python - 正则表达式:匹配特定模式,如果匹配在特定上下文中则排除

用于检测损坏图像的 Python 脚本

python - 压缩具有缺失值的数据帧行

python - 如何在 pandas 数据帧上生成具有随机值的合成数据?

python - Django - 更改一对多关系中相关对象的值

python - 用python安装gtk、webkit和jswebkit

python - 使用 str.contains 查看列表中的哪些单词在每个项目中