소품집

[KT AIVLE] pandas 조건 걸고 컬럼 추가하기 본문

AI/KT 에이블스쿨

[KT AIVLE] pandas 조건 걸고 컬럼 추가하기

sodayeong 2022. 8. 7. 16:21

pandas.DataFrame.isin()  옵션

교육 도중 문제 풀다 isin 옵션을 적용해서 풀면 간단하게 풀 수 있는 걸 확인해서 정리해보려 한다. 

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

 

pandas.DataFrame.isin — pandas 1.4.3 documentation

The result will only be true at a location if all the labels match. If values is a Series, that’s the index. If values is a dict, the keys must be the column names, which must match. If values is a DataFrame, then both the index and column labels must ma

pandas.pydata.org

 

DataFrame.isin(values)

values : 데이터프레임, 딕셔너리, 시리즈 등

return : 데이터프레임이 반환

 

근데 isin 조건에서 수치형일 때 조건 범위는 지정하지 못하는 것 같다. 

따라서 범주형 변수를 대치하고자 할 때 더 적합한 것 같다. 

ex) isin(['Sat, 'Sun']) 

# isin 대치
df['lenght3'] = 0
df.loc[df['sepal length (cm)'].isin([4.0, 4.1]), 'length3']= 1​

 

그래서 where 문이나 for문 조건으로 수치형 변수를 대치해보면 다음과 같다. 

# where 조건으로 대치
df['length2'] = np.where(df['sepal length (cm)'].values >= 4.0, 1, 0)​
# for 문 대치
df['length'] = [1 if i else 0 for i in df['sepal length (cm)']>=4.0]
728x90
Comments