Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas – 둘 이상의 열에서 선행 및 후행 공백 제거

<시간/>

선행 또는 후행 공백을 제거하려면 strip() 메서드를 사용하십시오. 먼저 "제품 범주", "제품 이름" 및 "수량" 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]})

둘 이상의 열에서 공백 제거 -

dataFrame['Product Category'].str.strip()
dataFrame['Product Name'].str.strip()

예시

다음은 전체 코드입니다 -

import pandas as pd

# create a dataframe with 3 columns
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]})

# removing whitespace from more than 1 column
dataFrame['Product Category'].str.strip()
dataFrame['Product Name'].str.strip()

# dataframe
print"Dataframe after removing whitespaces...\n",dataFrame

출력

이것은 다음과 같은 출력을 생성합니다 -

Dataframe after removing whitespaces...
   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