아이공의 AI 공부 도전기

python pandas dataframe replace가 작동하지 않을 때 해결법

 

 

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

 

pandas.DataFrame.replace — pandas 1.4.2 documentation

Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating poin

pandas.pydata.org

 

https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html

 

pandas.Series.replace — pandas 1.4.2 documentation

Regular expressions will only substitute on strings, meaning you cannot provide, for example, a regular expression matching floating point numbers and expect the columns in your frame that have a numeric dtype to be matched. However, if those floating poin

pandas.pydata.org

일반적으로 dataframe 혹은 series에 있는 특정 값을 교체하고자 할 때 replace를 사용한다.

 

이때 필수적으로 사용되는 것은 DataFrame.replace(to_replace, value) 이다.

 

그러나 아래 코드와 같이 replace를 시도해보았지만 작동하지 않았다.

 

df_all['Title'].replace(['Miss', 'Mrs','Ms', 'Mlle', 'Lady', 'Mme', 'the Countess', 'Dona'], 'Miss/Mrs/Ms', inplace=True)
df_all['Title'].replace(['Dr', 'Col', 'Major', 'Jonkheer', 'Capt', 'Sir', 'Don', 'Rev'], 'Dr/Military/Noble/Clergy', inplace=True)

 

https://stackoverflow.com/questions/37593550/replace-method-not-working-on-pandas-dataframe

 

replace() method not working on Pandas DataFrame

I have looked up this issue and most questions are for more complex replacements. However in my case I have a very simple dataframe as a test dummy. The aim is to replace a string anywhere in the

stackoverflow.com

이유를 찾기 위해 다방면으로 알아보았는데 regex=True로 설정하면 되었다.

 

df_all['Title'].replace(['Miss', 'Mrs','Ms', 'Mlle', 'Lady', 'Mme', 'the Countess', 'Dona'], 'Miss/Mrs/Ms', inplace=True, regex=True)
df_all['Title'].replace(['Dr', 'Col', 'Major', 'Jonkheer', 'Capt', 'Sir', 'Don', 'Rev'], 'Dr/Military/Noble/Clergy', inplace=True, regex=True)

 

api의 수정이 있는 것 같다.

 

 

 

 

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading