I have a list of index values. The values in the list can be repeated multiple times.
index_list = [1,3,4,3,2,20,55,30,45]
I want to query a pandas dataframe and extract the the values with indexes matching the values in the index_list
- If the same index is present multiple times I want to extract the value multiple times.
- The order of selected value must match the order of the index_list.
The index_list can be pretty long (100000) and the df quite small (400 rows, 2 columns)
The solution I used is based on a loop:
all_selected_values = []
for idx in index_list:
all_selected_values.append(df.loc[df.index == idx,'selected_column'].values[0])
This works but can be quite slow.
Is there a more efficient way to do it?
Thanks!