如何在 pandas.DataFrame 中找到某个值的位置?

How do I find the position of a value in a pandas.DataFrame?

我想在下面的 DataFrame 的索引中搜索 'row3',对于从零开始的数组,它应该是 2。

import numpy as np
import pandas as pd

rownames = ['row1', 'row2', 'row3', 'row4', 'row5']
colnames = ['col1', 'col2', 'col3', 'col4']

# Create a 5 row by 4 column array of integers from 0 to 19
integers = np.arange(20).reshape((5, 4))
table = pd.DataFrame(integers, index=rownames, columns=colnames)

有return行数'row3'的函数吗? 在此先感谢您的帮助。

您可以使用 Index.get_loc (docs):

>>> table.index.get_loc("row3")
2
>>> table.iloc[table.index.get_loc("row3")]
col1     8
col2     9
col3    10
col4    11
Name: row3, dtype: int64
>>> table.loc["row3"]
col1     8
col2     9
col3    10
col4    11
Name: row3, dtype: int64

但这是一种有点不寻常的访问模式——我自己从来不需要它。

您可能只是找到从 'row1' 到 'row3' 的 df 的长度并将其减 1(如果您从 0 开始计数)。

s = 'row3'
print(s,'number is', len(table['row1':s]) - 1)

returns

row3 number is 2