from 데이터 전처리 50 문제

JS·2025년 4월 25일
post-thumbnail

변수형별로 나누기

num = []
obj = []

for col in list(df.columns):
    if df[col].dtype == "object":
        obj.append(col)
    else:
        num.append(col)

print(f"* 숫자형 변수 : {num}")
print(f"* 문자형 변수 : {obj}")

Pivot_table 활용

df["InvoiceDate"] = pd.to_datetime(df["InvoiceDate"])
df["year"] = df["InvoiceDate"].dt.year
df["month"] = df["InvoiceDate"].dt.month

pd.pivot_table(df, index=["year", "month"], values="Country", aggfunc="count")

Label Encoding

from sklearn.preprocessing import LabelEncoder 

LabelEncoder = LabelEncoder()

for col in categorical_list:
    df[col] = LabelEncoder.fit_transform(df[col])

df[categorical_list]

NaN drop

df = pd.read_csv('/content/sample_data/exam01.csv', encoding='ISO-8859-1')

df.dropna(subset = ['Description'], axis = 0, inplace = True)

df.info()

Zero Ratio 출력

숫자형 변수에서 만

num = []
for col in df.columns:
    if df[col].dtype == "object":
        continue
    num.append(col)

col_have_zero = []
for col in num:
    print(f'zero_cnt of {col}=' , len(df[df[col] == 0]) , f', zero_ratio of {col} = ', len(df[df[col] == 0]) / len(df[col]) )

Data Type 재정의

df['CustomerID'] = df['CustomerID'].astype(str).str.rstrip('.0')

정답은

# ▶ dtype 명령어를 활용하여 CustomerID col의 현재 데이터 타입 확인
df['CustomerID'].dtype # float 타입으로 선언되어 있음
# ▶ CustomerID 
df['CustomerID'].head() # 문자로 변환하기 전에 소수점으로 표현된 내용 삭제 필요
# ▶ NaN Value가 존재하면 astype 명령어 실행 시 error가 발생하기 때문에, 사전에 NaN value처리가 필요함
df['CustomerID'] = df['CustomerID'].fillna(00000)
# ▶ float type을 int형태로 변환하여 소수점 자리를 삭제하고, 다시 astype(str) 명령어를 통해 문자열 형태로 변환
df['CustomerID'] = df['CustomerID'].astype(int).astype(str)
df['CustomerID'].head()

중복 데이터 처리

내답

df2 = df.drop_duplicates()
print(len(df), len(df2))

정답

# ▶ 중복된 데이터 개수 확인
df.duplicated().value_counts()
# ▶ duplicated(keep=False) 명령어를 활용하면, 모든 중복된 row에 대해서 True를 부여하므로 중복된 데이터를 직접 확인할 수 있음
df[df.duplicated(keep=False)].sort_values(by=list(df.columns)).head()
# ▶ drop_duplicates 명령어를 통해 모든 col이 중복되는 row를 삭제한다. 
df_unique = df.drop_duplicates()# ▶ 중복 제거 전/후 개수 비교
len(df), len(df_unique)

음수값 제거

# ▶ 문제의 조건에 맞게 음수값을 제거하고 df를 다시 구성
df = df[df['Quantity']>0]
df = df[df['UnitPrice']>0]

유니크값 개수 출력

# ▶ for문 활용 df.columns list를 인자로 전달받아서, nunique() 명령어를 통해 Col별 Unique한 val를 출력
for i in df.columns :
  print(f'{i} / Unique val : {df[i].nunique()}')

연속형 변수 구간화(Binning)

# ▶ UnitPrice 조건 적용 
df = df[df['UnitPrice']>0]
df['UnitPrice'].describe()

# ▶ 상위 결과에서 [0, 25%, 50%, 75%, max] 값들을 활용하여, pd.cut 수행 
df['UnitPrice_gp'] = pd.cut(df['UnitPrice'], bins = [0, 1.25, 2.08, 4.13, 38970], labels= ['gp1', 'gp2', 'gp3', 'gp4'])
df.groupby('UnitPrice_gp')['InvoiceNo'].count()

특정 조건 만족 데이터 추출(1)

df[(df["Quantity"] >= 10) & (df["InvoiceDate"].str.contains("12/1/2010"))]
len(df[(df["Quantity"] > 10) & (df["InvoiceDate"].str.contains("12/1/2010"))])

특정 조건 만족 데이터 추출(2)

🔒문제설명


  • 주어진 Data를 Read하고,다음 명령어를 사용하여 특정 조건에 맞는 데이터를 추출하시오

출력형태

* isin()과 notnull() 명령어를 사용할 것
* StockCode가 (84029E, 84406B, 85123A)를 포함하는 데이터
* CustomerID가 Null 값이 아닌 데이터 
* 상위 2조건을 동시에 만족하는 데이터 추출
# ▶ 문제에서 요구한 Stockcode가 포함되어 있는 데이터 추출
df[df['StockCode'].isin(['84029E', '84406B', '85123A']) & df['CustomerID'].notnull()]
profile
Don Quixote

0개의 댓글