Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vectorized Lookup in Dataframe Using Numpy Array

Given a numpy array such as the one below, is it possible to use vectorization to return the associated value in column HHt without using a for loop?

ex_arr = [2643, 2644, 2647]

for i in ex_arr:

    h_p = df.at[i, "HHt"]

Example df:

HHt
2643 1
2644 2
2645 3
2646 4
2647 5
2648 6
2649 7
2650 8

Expected result:
1
2
5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use DataFrame.loc, if need list or array add Series.to_list or Series.to_numpy:

print (df.loc[ex_arr,'HHt'].to_list())
[1, 2, 5]

print (df.loc[ex_arr,'HHt'].to_numpy())
[1 2 5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading