You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数据集全行列搜索指定值:替代df.loc的可行方案咨询

Full DataFrame Search for Specific Values in Pandas

Got it, let's figure out how to search every row and column in your Pandas DataFrame for specific values like 'john' and 'tom'. Your initial attempt with iloc didn't work because isin() is a method for Series/DataFrames, not strings, and iloc expects positional indices instead of boolean checks across the whole table.

Here are a few practical approaches tailored to different needs:

1. Get All Rows That Contain Any Target Value

If you just want to retrieve entire rows where at least one cell matches your target values, use isin() combined with any(axis=1):

import pandas as pd

# Sample DataFrame for demonstration
df = pd.DataFrame({
    'name': ['alice', 'john', 'bob'],
    'age': [30, 'tom', 25],
    'city': ['new york', 'london', 'john']
})

target_values = ['john', 'tom']
# Filter rows where any column has a target value
matching_rows = df[df.isin(target_values).any(axis=1)]
print(matching_rows)

This works because df.isin(target_values) creates a boolean DataFrame where each cell is True if it matches a target value. any(axis=1) then checks if there's at least one True in each row, giving us a boolean Series to filter the original DataFrame.

2. Find Exact Cell Positions and Values

If you need to know exactly which cells (row index + column name) contain your target values, use stack() to flatten the DataFrame into a Series, then filter:

# Get all matching cells with their positions
matching_cells = df.stack()[df.stack().isin(target_values)]
print(matching_cells)

The output will look like this, clearly showing where each match is located:

0  city     john
1  name     john
1  age       tom
2  city     john
dtype: object

3. Manual Row/Column Traversal (For Small DataFrames)

If you specifically want to loop through every row and column (though this is less efficient for large datasets), you can use iterrows():

matches = []
for row_idx, row in df.iterrows():
    for col_name in df.columns:
        cell_value = row[col_name]
        if cell_value in target_values:
            matches.append({
                'row_index': row_idx,
                'column': col_name,
                'value': cell_value
            })

# Print formatted results
for match in matches:
    print(f"Found {match['value']} at row {match['row_index']}, column {match['column']}")

This is useful if you need to perform custom actions for each matching cell, but stick to the first two methods for better performance with big datasets.


内容的提问来源于stack exchange,提问作者asmgx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:12:30