如何在pandas DataFrame中根据指定值获取列索引?
Hey there! Let's work through how to find the column index for the value "Mobile : 0" in your DataFrame. You mentioned iloc isn't working here—and that makes sense, since iloc is designed for position-based access, not searching for specific values. Here are a couple of reliable approaches to solve this:
Method 1: Boolean Filtering + Column Index Lookup
This method uses boolean matching to identify columns containing your target value, then converts that column label to its integer index:
import pandas as pd import numpy as np # Your input data converted to DataFrame data = [['25362438,25383532 Mobile : 8691017781,8691017798', np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 'Mobile : 0', np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]] df = pd.DataFrame(data) target_value = "Mobile : 0" # Step 1: Find columns that contain the target value matching_columns = df.columns[df.eq(target_value).any()] # Step 2: Convert the column label to its integer index column_index = df.columns.get_loc(matching_columns[0]) print(column_index) # Output: 16
How this works:
df.eq(target_value)creates a boolean DataFrame where each cell isTrueif it matches your target value, otherwiseFalse..any()checks each column to see if there's at least oneTrue(i.e., the column contains the target value).df.columns.get_loc()converts the column label (in your case, an integer like16) to its corresponding position—this is especially handy if your columns have non-integer names later on.
Method 2: Flatten Data with stack()
Another approach is to flatten the DataFrame into a Series (automatically removing NaN values), then extract the column index from the resulting multi-index:
# Flatten the DataFrame to a Series (drops NaNs automatically) stacked_data = df.stack() # Find the row where the value matches, then get the column index matching_entry = stacked_data[stacked_data == target_value].index[0] column_index = matching_entry[1] # The second element of the index tuple is the column print(column_index) # Output: 16
How this works:
stack()pivots column labels into the row index, creating a multi-index (row number, column number) for each non-NaN value.- We filter the Series to find entries matching the target, then pull the column index directly from the multi-index tuple.
Why iloc isn't the right tool here
iloc requires you to already know the position of the row/column you want to access. Since you're trying to search for a value to find its position, iloc doesn't support this directly—you need to use value-matching operations first, like the ones above.
内容的提问来源于stack exchange,提问作者arun

