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

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

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.

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

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?

>Solution :

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
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