-
[Python Pandas] Pandas Dataframe에서 조건으로 column(열) 값 바꾸는 다양한 방법IT/Pandas 2022. 10. 19. 23:05
본 포스팅은 "https://www.geeksforgeeks.org/how-to-replace-values-in-column-based-on-condition-in-pandas/" 의 내용을 기반으로 작성했습니다.
Pandas 데이터프레임에서 조건과 함께 값을 바꾸는 다양한 방법을 알아봅시다.
방법 1. Dataframe.loc[ ] 사용하기.
첫 번째 방법은 dataframe.loc[]를 사용하는 방법입니다.
아래의 순서 설명은 이해를 돕기 위한 설명으로 실제 연산 과정과는 다릅니다다.
Example 1.
import pandas as pd import numpy as np # data Student = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'], } # creating a Dataframe object df = pd.DataFrame(Student) # Applying the condition # "gender" 칼럼에서 값이 "male"인 모든 행을 찾고 "gender" 칼럼의 값을 1로 변경 df.loc[df["gender"] == "male", "gender"] = 1
Output 1.
방법 2. numpy.where() 함수 사용하기
두 번째 방법은 numpy 라이브러리에서 numpy.where() 함수를 사용하는 방법입니다.
해당 함수는 반드시 조건과 참일 때 변경할 값과 거짓일 때 변경할 값을 지정해줘야 합니다.
Example1.과 동일한 예제에서 값이 "female"을 0, "male"을 1로 변경해보도록 하겠습니다.
Example 1.과 동일한 예제임으로 값을 변경하는 실행 부분의 코드만 나타냈습니다.
Example 2.
# Applying the condition df["gender"] = np.where(df["gender"] == "female", 0, 1)
Output 2.
방법 3. Dataframe.mask() 메서드 사용하기
세 번째 방법은 Pandas의 masking 기능을 사용하는 방법입니다.
특정 행 또는 열에서 조건에 맞는 값을 찾아서 원하는 값으로 변경이 가능합니다.
2가지 예제로 mask() 메서드를 사용해보겠습니다.
Example 3.
# 1번째 변경 예제 df['gender'].mask(df['gender'] == 'female', 0, inplace=True) # 2번째 변경 예제 df['math score'].mask(df['math score'] >=60 ,'good', inplace=True)
Output 3.
'IT > Pandas' 카테고리의 다른 글
[Python Pandas] 데이터 분할, 데이터 균등 분할 (cut, qcut) (0) 2022.09.27