我想在下面的数据帧索引中搜索'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)
有没有返回"row3"行号的函数?提前感谢任何帮助。
您可以使用
Index.get_loc
(文档):
>>> 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)
返回
row3 number is 2