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

如何以最优方式打印Pandas DataFrame指定行的索引?

获取Pandas DataFrame某一行索引的最优方法

没问题,这其实是新手常遇到的小疑问,我来给你讲清楚~

首先假设你的DataFrame是类似这样的(以Country列为索引):

import pandas as pd

# 示例DataFrame
data = {'Population': [331002651, 1439323776],
        'Capital': ['Washington D.C.', 'Beijing']}
df = pd.DataFrame(data, index=['United States', 'China'])

下面是几种高效的方法,根据你的使用场景选择即可:

  • 方法一:选中行后用.name属性获取索引
    不管你是用loc(按索引名选行)还是iloc(按位置选行),选中的行本质是一个Series对象,它的.name属性就是对应的索引值:

    • 用loc的情况:
      selected_row = df.loc['United States']
      print(selected_row.name)  # 输出: United States
      
    • 用iloc的情况:
      selected_row = df.iloc[0]  # 选中第一行
      print(selected_row.name)  # 输出: United States
      
  • 方法二:直接通过.index属性获取指定行的索引
    如果你不需要先取出整行,只想直接拿到某一行的索引,用df.index结合位置或条件会更高效:

    • 按位置取:
      print(df.index[0])  # 输出: United States
      
    • 如果是按条件筛选后取索引(比如找Population大于3亿的国家索引):
      target_index = df[df['Population'] > 300000000].index[0]
      print(target_index)  # 输出: United States
      

你提到的df.idxmax()确实是用来获取某列最大值对应的索引,和你现在的需求不匹配,所以不用考虑这个方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:28:11