분석 Python/Pandas Tip
[Pandas] 조건걸고 새로운 컬럼 추가하기
데이터분석뉴비
2020. 8. 12. 23:51
728x90
https://signing.tistory.com/55#comment5838430
[Tips] 조건걸고 새로운 컬럼 추가하기 in Pandas DataFrame
R에서는 대부분의 핸들링을 자유롭게 하던 나는 파이썬으로 그 작업들을 하나씩 진행하고자 한다. 분석을 진행하기 위해서 데이터를 내가 원하는 모양으로 맞춰줄 필요가 있다. 현재 내가 분석�
signing.tistory.com
기존 signing님의 방법 (List Comprehension)
iris['new_column'] = ['Large' if t else 'Small' for t in list(iris['Sepal.Length'] > 4)]
사전을 활용하여 값 변환해주기
iris = sns.load_dataset("iris")
dict_ = {True : "Large", False : "Small" }
iris["new_columns"] = [dict_[t] for t in list(iris["sepal_length"] > 5)]
iris.head()
np.where를 사용해서 값 변환해주기
iris["new_columns"] = np.where( iris["sepal_length"].values > 5 , "Large","Small" )
iris.head()
apply를 사용해서 대체하기
def func(x) :
if x > 5 :
return "Large"
else :
return "Small"
iris["new_columns"] = iris["sepal_length"].apply(lambda x : func(x))
728x90