Why I got KeyError in loop "for" with regular expressions?

Question:

I got pandas.Series with few values.

money = pd.Series(df_t['Сокращенное наименование '].unique())

0    USDCNY_TOM
1    USDRCNY_TOD
dtype: object

My regular expression:

m_trim = re.compile(r'_TOM$|_TOD$')

When I run this code, it’s works.

m_trim.sub('', money[0])

Result is: 'USDCNY'.

But then I trying to make loop:

for m in money:
    money[m] = m_trim.sub('', money[m])

I get KeyError: 'USDCNY_TOM'.

Thay am I doing wrong?

Asked By: John Doe

||

Answers:

for m in money is looping over the values of the Series. Thus money[m] is incorrectly trying to use the values as indices.

Use:

money = money.replace(m_trim, '', regex=True)

# or
money = money.str.replace(m_trim, '', regex=True)

Fix of your loop:

for i, m in money.items():
    money[i] = m_trim.sub('', m)

Or:

for i in money.index:
    money[i] = m_trim.sub('', money[i])

Output:

0     USDCNY
1    USDRCNY
Name: Сокращенное наименование , dtype: object
Answered By: mozway
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.