如何在Pandas中获取单元格所在列及每行最大值对应列?
Hey there! Let's break down your two Pandas questions clearly and practically:
The approach depends on what info you already have about the target cell:
If you know the cell's positional indices (row number + column number)
Usedf.columns[col_index]to pull the column name directly. Here's an example:import pandas as pd df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6], 'C': [7,8,9]}) # Get column for the cell at row 1, column 1 (value = 5) column_name = df.columns[1] print(column_name) # Output: 'B'If you know the row label and the cell's value
Combine boolean indexing withidxmax()to locate the column where the value matches. For instance, to find the column in row 'Y' with value 50:df = pd.DataFrame({'A': [10,20,30], 'B': [40,50,60], 'C': [70,80,90]}, index=['X','Y','Z']) target_value = 50 column_name = df.loc['Y'].eq(target_value).idxmax() print(column_name) # Output: 'B'
This is super straightforward with Pandas' built-in idxmax() method—just specify axis=1 to operate row-wise:
# Using the same DataFrame from above max_columns = df.idxmax(axis=1) print(max_columns) # Output: # X C # Y C # Z C # dtype: object
A quick heads-up: If a row has multiple cells with the same maximum value, idxmax() will return the first column that holds the maximum. If you need all columns with the maximum value for each row, use apply() with a lambda function:
# Modify the DataFrame to create a tie in row 'Y' df.loc['Y', 'B'] = 80 all_max_columns = df.apply(lambda row: row[row == row.max()].index.tolist(), axis=1) print(all_max_columns) # Output: # X [C] # Y [B, C] # Z [C] # dtype: object
内容的提问来源于stack exchange,提问作者Jenna Moore

