如何找到包含特定字符串的 DataFrame 条目的索引,并且这些字符串不是列名称。
indice0 = np.argwhere(df=='apple')
indice1 = np.argwhere(df=='banna')
indice2 = np.argwhere(df=='orange')
我知道上面的代码可以工作,但是有没有一种方法可以简化它,例如使用 for 循环。例如,如果我只知道字符串的一部分,上面的代码似乎不起作用
indice0 = np.argwhere(df=='pple')
indice1 = np.argwhere(df=='anna')
indice2 = np.argwhere(df=='range'
还有其他方法来定位索引吗?
对于第一个问题,您可以直接索引条件成立的
index
。将此与 isin([...])
结合起来,您的示例将变为:
indices = df.index[df.isin(["apple", "bananna", "orange"])]
对于第二个,我不知道后缀的
isin
的一般情况版本,但您可以通过 df.index[df.str.endswith("pple")]
单独完成。或者,如果变体很少,那么您可以手动创建一个正则表达式,例如 df.index[df.str.contains("pple|ananna|range$")]