Unable to return index from Series using value match for numeric values

Question:

A pandas Series object is created from a list of numbers and characters, charSeries, copied below for reference.

A random five digit string of characters and numbers, created from the below list, is made:

code_core = Q5YUO

Each character in code_core is iterated through to get the corresponding index:

for character in code_core:
    index_tosum = charSeries[charSeries == character].index(0)

This works for all alphabet characters. However for any number an error is returned. In the above core_core, an error is returned for character ‘5’:

    return getitem(key)
IndexError: index 0 is out of bounds for axis 0 with size 0

It is found that for 5, or any number,

charSeries[charSeries == character]

is empty. I do not see why this is as 5 is one of the values in the Series below and has an index of 5.

What is the error in my code or my approach?

0     0
1     1
2     2
3     3
4     4
5     5
6     6
7     7
8     8
9     9
10    B
11    C
12    D
13    F
14    G
15    H
16    J
17    K
18    L
19    M
20    N
21    P
22    Q
23    R
24    S
25    T
26    V
27    W
28    X
29    Y
30    Z
Asked By: acolls_badger

||

Answers:

IIUC use next with iter with default value if no match, also if mixed numeric and string values convert them to strings by astype:

code_core = 'Q5YUO'

for character in code_core:
    out = next(iter(charSeries.index[charSeries.astype(str) == character]), 'no match')
    print (out)
    22
    5
    29
    no match
    no match
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.