Python 从 DataFrame 行获取行索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35238339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:10:05  来源:igfitidea点击:

Get row index from DataFrame row

pythonpandasindexing

提问by orange

Is it possible to get the row number (i.e. "the ordinal position of the index value") of a DataFramerow without adding an extra row that contains the row number (the index can be arbitrary, i.e. even a MultiIndex)?

是否可以在DataFrame不添加包含行号的额外行(索引可以是任意的,即甚至是 MultiIndex)的情况下获取行的行号(即“索引值的序数位置” )?

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [2, 3, 4, 2, 4, 6]})
>>> result = df[df.a > 3]
>>> result.iloc[0]
a    4
Name: 2, dtype: int64
# but how can I get the original row index of iloc[0] in df?

I could have done df['row_index'] = range(len(df))which would maintain the original row number, but I am wondering if Pandas has a built-in way of doing this.

我本可以df['row_index'] = range(len(df))保持原始行号,但我想知道 Pandas 是否有内置的方法来做到这一点。

采纳答案by EdChum

Access the .nameattribute and use get_loc:

访问.name属性并使用get_loc

In [10]:
df.index.get_loc(result.iloc[0].name)

Out[10]:
2