Python数据集全行列搜索指定值:替代df.loc的可行方案咨询
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

