Development/Python
[Python] 한 Column에 대해서 Dictionary를 이용해 값을 바꾸는 방법
성딱이
2021. 9. 30. 12:11
반응형
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':[10, 20, 10, 20, 30, 40],
'col2': ['US', 'BR','JP', 'KR', 'JP', np.nan]}
)
dic = { 'US':"US10YT=RR"
, 'GB':"GB10YT=RR"
, 'KR':"KR10YT=RR"
, 'BR': 'BR10YT=RR'
, 'JP': 'JP10YT=RR'}
df
col1 col2
0 10 US
1 20 BR
2 10 JP
3 20 KR
4 30 JP
5 40 NaN
방법 1.
df['col2'].apply(lambda x : x.replace(x, dic[x]))
방법 2.
df['col2'].apply(lambda x : dic[x])
방법 3. -> 선택
df['col2'].map(dic)
# 추가 활용 방법(NaN처리도 같이!)
df['col2'].map(dic).fillna(df['col1']) # 'col1' 컬럼의 값으로 NA 채움
df['col2'].map(dic).fillna(1) # 1로 NA 채움
방법1, 2의 경우에는 모두 동작하긴 했으나, 2가지 상황에서 에러가 발생
1) Dictionary에 있는 key가 존재하지 않을 경우,
2) NaN이 존재하는 경우
따라서 방법 3 짱
출처 : https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict
반응형