Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to get the integer index of a key in pandas

Tags:

python

pandas

How can I get the integer location of a key to a pandas index as quickly as possible?

eg, given pd.DataFrame(data=np.asarray([[1,2,3],[4,5,6],[7,8,9]]), index=['alice', 'bob', 'charlie'])

what is the fastest way to go from 'bob' to 1

like image 990
N. McA. Avatar asked Aug 03 '15 17:08

N. McA.


People also ask

Is Pandas query faster than LOC?

The query function seams more efficient than the loc function. DF2: 2K records x 6 columns. The loc function seams much more efficient than the query function.

How do I select a specific index in Pandas?

If you'd like to select rows based on integer indexing, you can use the . iloc function. If you'd like to select rows based on label indexing, you can use the . loc function.


2 Answers

Use get_loc, it was made for this purpose!

df.index.get_loc('bob')
like image 171
AZhao Avatar answered Nov 02 '22 13:11

AZhao


Not sure if it is the fastest but you can use index.get_loc:

df = pd.DataFrame(data=np.asarray([[1,2,3],[4,5,6],[7,8,9]]), index=['alice', 'bob', 'charlie'])

print(df.index.get_loc("bob"))
1
like image 21
Padraic Cunningham Avatar answered Nov 02 '22 13:11

Padraic Cunningham