pandas 在列匹配特定值的数据框中获取整数行索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37502298/
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
Get integer row-index in dataframe where column matches specific value
提问by Ned Hulton
Given a Pandas dataframe, where one of the columns looks like this:
给定一个 Pandas 数据框,其中一列如下所示:
Date
2016-04-15
2016-04-14
2016-04-13
2016-04-12
2016-04-11
2016-04-08
How do I get the row-index of a particular value assuming that values are unique?
假设值是唯一的,如何获取特定值的行索引?
For example, "2016-04-13" would return 2
例如,“2016-04-13”将返回 2
回答by ayhan
With boolean indexing, you can slice the dataframe to get only the rows where the date equals "2016-04-13" and get the index of the slice:
使用布尔索引,您可以对数据帧进行切片以仅获取日期等于“2016-04-13”的行并获取切片的索引:
df[df.Date == "2016-04-13"].index
Out[37]: Int64Index([2], dtype='int64')
With the uniqueness assumption, there will be only one element in that array, so you can take the 0th element:
根据唯一性假设,该数组中将只有一个元素,因此您可以取第 0 个元素:
df[df.Date == "2016-04-13"].index[0]
Out[38]: 2
回答by Tanu
Use df.index.get_loc('2016-04-14')
to get the integer location for requested label. This will return 1
as intital starts from 0
. So you can add one to get the index value as 2
使用df.index.get_loc('2016-04-14')
以获取所需标签的整数位置。这将1
在 intital 从 开始时返回0
。所以你可以加一个来得到索引值2
回答by Ned Hulton
df['Date'].values.tolist().index("2016-04-13")
will return 2
df['Date'].values.tolist().index("2016-04-13")
将返回 2