2

I have a pandas dataframe which is indexed by strings. Let's say my index looks like df.index = ['AA','AB','AC',...] and I want to access df.loc['AC':'AE'], which works well.

Is there any way to get the position of these indices, giving me ['AC':'AE'] => [2,3,4]? I know there is df.index.get_loc('AC') => 2 but this works only for single values and not for lists.

2 Answers 2

2

Use:

df = pd.DataFrame({'a': [5,6,7,8, 10]}, index=['AA','AB','AC','AD','AE'])

pos = list(range(df.index.get_loc('AC'), df.index.get_loc('AE') + 1))
print (pos)
[2, 3, 4]

Another solutions with Index.searchsorted:

pos = list(range(df.index.searchsorted('AC'), df.index.searchsorted('AE') + 1))
print (pos)
[2, 3, 4]

a = df.index.searchsorted(['AC', 'AE'])
pos = list(range(a[0], a[1] + 1))
print (pos)
[2, 3, 4]
Sign up to request clarification or add additional context in comments.

Comments

1

You can define a function to extract the integer range:

df = pd.DataFrame(np.arange(7), index=['AA','AB','AC','AD','AE','AF','AG'])

def return_index(df, a, b):
    col_map = df.index.get_loc
    return np.arange(col_map(a), col_map(b)+1)

res = return_index(df, 'AC', 'AE')

print(res)

array([2, 3, 4])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.