Pandas DataFrame의 문자열 데이터에서 앞뒤 공백(leading/trailing whitespace)을 제거하려면 strip() 메서드를 사용하면 됩니다. 먼저 필요한 Pandas 라이브러리를 별칭(alias)과 함께 임포트합니다.
import pandas as pd
이제 3개의 열(column)을 가진 DataFrame을 생성해 보겠습니다. 첫 번째 열인 'Product Category'에는 의도적으로 앞뒤 공백이 포함된 값들이 들어 있습니다.
dataFrame = pd.DataFrame({
'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],
'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],
'Quantity': [10, 50, 10, 20, 25, 50]
})단일 열에서 공백 제거하기
'Product Category' 열 하나에서만 공백을 제거하려면 해당 열에 str.strip()을 적용한 뒤, 그 결과를 다시 열에 할당해야 실제 DataFrame에 반영됩니다.
dataFrame['Product Category'] = dataFrame['Product Category'].str.strip()
전체 예제 코드
다음은 위 과정을 모두 포함한 완성된 코드입니다.
import pandas as pd
# 3개의 열을 가진 DataFrame 생성
dataFrame = pd.DataFrame({
'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],
'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Refrigerators', 'Chairs', 'Diaries'],
'Quantity': [10, 50, 10, 20, 25, 50]
})
# 공백 제거 전 상태 확인
print("공백 제거 전 DataFrame:\n", dataFrame)
# 'Product Category' 열의 앞뒤 공백 제거 후 결과 재할당
dataFrame['Product Category'] = dataFrame['Product Category'].str.strip()
# 공백 제거 후 결과 출력
print("\n공백 제거 후 DataFrame:\n", dataFrame)출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
공백 제거 후 DataFrame: Product Category Product Name Quantity 0 Computer Keyboard 10 1 Mobile Phone Charger 50 2 Electronics SmartTV 10 3 Appliances Refrigerators 20 4 Furniture Chairs 25 5 Stationery Diaries 50
추가로 알아두면 좋은 팁
1. lstrip()과 rstrip()
공백을 제거하는 방향을 지정하고 싶다면 아래 메서드를 사용할 수 있습니다.
str.lstrip(): 문자열 앞쪽(왼쪽) 공백만 제거str.rstrip(): 문자열 뒤쪽(오른쪽) 공백만 제거
2. 모든 문자열 열에 한 번에 적용하기
열이 많을 경우 반복문 없이 한 번에 처리할 수도 있습니다.
str_cols = dataFrame.select_dtypes(include='object').columns dataFrame[str_cols] = dataFrame[str_cols].apply(lambda col: col.str.strip())
이처럼 strip() 계열 메서드를 활용하면 외부 데이터(CSV, Excel 등)를 불러올 때 흔히 발생하는 불필요한 공백 문제를 간단하게 해결할 수 있습니다.