获取 Pandas 中具有特定值的单元格的行和列

Gab*_*iel 4 excel dataframe pandas

我正在尝试使用 Pandas 读取未格式化的 Excel 电子表格。一张表中有多个表,我想将这些表转换为数据框。由于它尚未以传统方式“索引”,因此没有有意义的列或行索引。有没有办法搜索特定值并获取行、列所在的位置?例如,假设我想获取包含字符串“Title”的所有单元格的行列号。

我已经尝试过 DataFrame.filter 之类的东西,但只有在有行和列索引时才有效。

小智 6

使用 NaN 创建一个 df ,其中没有找到 your_value 。
删除所有不包含该值的行。
删除所有不包含值的列

a = df.where(df=='your_value').dropna(how='all').dropna(axis=1)
Run Code Online (Sandbox Code Playgroud)

获取行

a.index
Run Code Online (Sandbox Code Playgroud)

获取列

a.columns  
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 3

您可以进行一些冗长且难以阅读的列表理解:

# assume this df and that we are looking for 'abc'
df = pd.DataFrame({'col':['abc', 'def','wert','abc'], 'col2':['asdf', 'abc', 'sdfg', 'def']})

[(df[col][df[col].eq('abc')].index[i], df.columns.get_loc(col)) for col in df.columns for i in range(len(df[col][df[col].eq('abc')].index))]
Run Code Online (Sandbox Code Playgroud)

出去:

[(0, 0), (3, 0), (1, 1)]
Run Code Online (Sandbox Code Playgroud)

我应该注意这是(索引值,列位置)

如果您正在查找包含特定值的任何字符串,您也可以更改.eq()为:str.contains()

[(df[col][df[col].str.contains('ab')].index[i], df.columns.get_loc(col)) for col in df.columns for i in range(len(df[col][df[col].str.contains('ab')].index))]
Run Code Online (Sandbox Code Playgroud)