Programming/python

[python] data cleaning in pandas

그렉그의 2023. 6. 1. 15:16
import pandas as pd
In [40]:
df= pd.read_excel(f'/Users/grace/Desktop/Alex/Customer Call List.xlsx')
df
#중복 제거
df.drop_duplicates()
df
#마지막 컬럼 제거
df= df.drop(columns = 'Not_Useful_Column')
df
# 1. numeric 으로 다 만들기 using replace
# replace anything with empty string to nothing '[a-zA-Z0-9]' 해서 assign 한다음에 
# we need to change every thing into string first
# then use lambda to make it as 000-000-000
# get rid of nan, Na 
df['Phone_Number']= df['Phone_Number'].str.replace('[^a-zA-Z0-9]','')
df['Phone_Number'] = df['Phone_Number'].apply(lambda x: str(x))
df['Phone_Number'] = df['Phone_Number'].apply(lambda x: x[0:3] + "-" + x[3:6] + "-" + x[6:9])
df['Phone_Number'] = df['Phone_Number'].str.replace("nan--","")
df['Phone_Number'] = df['Phone_Number'].str.replace("na--","")
df['Phone_Number'] = df['Phone_Number'].str.replace("--","")

df['Last_Name']= df['Last_Name'].str.lstrip("/")
df['Last_Name'] = df['Last_Name'].str.lstrip("...")
df['Last_Name'] = df['Last_Name'].str.rstrip("_")
df
#address 를 Street_Address, State, Zip_Code로 str.split 해서 작성 , expand =True 추가
df[['Street_Address','State','Zip_Code']] = df['Address'].str.split(",",2, expand = True)
df
#Yes를 Y, No를 N 로 변환
df['Paying Customer'] = df['Paying Customer'].str.replace('Yes','Y')
df['Paying Customer'] = df['Paying Customer'].str.replace('No','N')
df['Do_Not_Contact'] = df['Do_Not_Contact'].str.replace('Yes','Y')
df['Do_Not_Contact'] = df['Do_Not_Contact'].str.replace('No','N')
df['Do_Not_Contact'] = df['Do_Not_Contact'].str.replace('NaN','')
df['Do_Not_Contact'] = df['Do_Not_Contact'].fillna('')

df
Out[71]:
#for 문 사용해서 Do_Not_Contact 열이 Y 일때 행 drop 하기(2차 배열 생각) drop 할 때 Inplace = True 포함
for x in df.index:
    if df.loc[x, 'Do_Not_Contact'] == 'Y':
        df.drop(x, inplace=True)

df
#for 문 사용해서 phone_NUmber 열이 Y 일때 행 drop 하기
for x in df.index:
    if df.loc[x, 'Phone_Number'] == '':
        df.drop(x, inplace=True)
df
#reset_index 하기 drop = True
df.reset_index(drop = True)

출처: alex the analyst