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