简体   繁体   中英

Get integer row-index in dataframe where column matches specific value

Given a Pandas dataframe, where one of the columns looks like this:

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

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:

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:

df[df.Date == "2016-04-13"].index[0]
Out[38]: 2

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['Date'].values.tolist().index("2016-04-13")将返回2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM