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

如何在Pandas中获取单元格所在列及每行最大值对应列?

Hey there! Let's break down your two Pandas questions clearly and practically:

问题1:如何在Pandas中获取某个单元格所在的列?

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)
    Use df.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 with idxmax() 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'
    
问题2:获取每行最大值所在的列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:33:13