[英]How do I find the position of a value in a pandas.DataFrame?
I want to search for 'row3' in the index of the DataFrame below, which should be 2 for a zero-based array.我想在下面的 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)
Is there a function which return the row number of 'row3'?是否有返回“row3”行号的函数? Thanks in advance for any help.
在此先感谢您的帮助。
You could use Index.get_loc
( docs ):您可以使用
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
But this is a somewhat unusual access pattern-- never need it myself.但这是一种有点不寻常的访问模式——我自己从不需要它。
You may just find the length of df from 'row1' till 'row3' and decrease it by 1 (if you are starting count from 0).您可能只是找到从“row1”到“row3”的 df 长度并将其减少 1(如果您从 0 开始计数)。
s = 'row3'
print(s,'number is', len(table['row1':s]) - 1)
returns返回
row3 number is 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.