24.10.21 Day67

최지원·2024년 10월 21일

데이터 불러오기

  • 엑셀 파일에서 원하는 데이터 가져오기
df_seoul = pd.read_excel('data/seoul.xlsx', sheet_name='Sheet1')
df_seoul.head(3)

print(df_seoul.iloc[0,0])
print(df_seoul.iloc[1,1])
print(df_seoul.iloc[0:2,0])
df_seoul = pd.read_excel('data/seoul.xlsx',sheet_name='Sheet1', index_col = 0) # 첫번째 열을 인덱스로 사용
df_seoul.head(3)
print(df_seoul.loc['성동구','1인세대비율'])
print(df_seoul.loc['성동구',['1인세대비율','2인세대비율']])

  • 필터링
# select * from df_seuol where 1인세대비율 >= 0.5
filtered_df = df_seoul[df_seoul['1인세대비율'] >= 0.5]
filtered_df

lambda식

  • 한줄로 쓰는 함수
def get_square(n):
    return n ** 2
print(get_square(3))

lambda_square = lambda x : x ** 2
print(lambda_square(3))
# SELECT
# CASE
#   WHEN 재산피해 <= 1000 THEN '소형화재'
#   ELSE '대형화재'
# END
df['화재크기분류'] = df['재산피해소계'].apply(lambda x : '소형' if x <= 1000 else '대형')
df.head(1)
  • 데이터프레임의 한 행씩 이 함수 호출
def classify_fire(row):
    if row['재산피해소계'] < 500:
        return '소형'
    elif row['재산피해소계'] < 10000:
        return '중형'
    else:
        return '대형'
df['화재크기분류'] = df.apply(classify_fire, axis=1)
df.head(2)

# 중형화재 데이터만 필터하여 출력
# 1. 재산피해액으로 필터 2. 중형화재로 필터
cond1 = df['재산피해소계'] >= 500
cond2 = df['재산피해소계'] < 10000
filtered_df = df[cond1 & cond2]
filtered_df['화재크기분류'].value_counts()
# python에서 pandas로 만든 데이터프레임에는 재산피해소계라는 열이 있다.
# 이 열을 기반으로 화재크기분류라는 열을 만들고 싶은데 그 규칙은 아래와 같다.

  • 삭제 : 행과 열 삭제
new_df = df.drop('연번',axis=1) # 열 삭제시 이름 지정
new_df.head(2)

df.drop(0, axis=0) # 행 삭제시 인덱스 지정
df.head(2)
  • 새로운 데이터프레임을 반환하지 않고 열 삭제
# inplace = True
df.drop('연번', axis=1, inplace=True)
  • 결측치가 존재하는 파일 불러오기
df_titanic= pd.read_csv('data/titanic.csv')
df_titanic.head(2)             # 파일이 제대로 들어왔는데 head(2)만 출력하여 확인
df_titanic.isna().head(3)      # isna 매서드를 사용하여 결측치 존재 여부 파악
df_titanic.info()
# select sum(재산피해소계) from 테이블
df['재산피해소계'].sum()
# select 시도, sum(재산피해소계) from 테이블 group by 시도
df.groupby('시도')['재산피해소계'].sum()
  • 2018, 2019년의 화재 데이터를 각각 로드
df_2018 = pd.read_csv('data/2018년화재.csv', encoding='cp949')
df_2019 = pd.read_csv('data/2019년화재.csv', encoding='cp949')
print('2018 shape: {}'.format(df_2018.shape))
print('2019 shape: {}'.format(df_2019.shape))
df_total['화재발생년월일'] = pd.to_datetime(df_total['화재발생년월일'])
# 연도 추출하여 새로운 열 생성
df_total['화재발생연도'] = df_total['화재발생년월일'].dt.year
df_total.head(2)
df_sales = pd.read_excel('data/adw.xlsx', sheet_name='인터넷판매')
df_customer = pd.read_excel('data/adw.xlsx', sheet_name='고객')

print('df_sales: {}'.format(df_sales.shape))
print('df_customer: {}'.format(df_customer.shape))
# select *
# from 인터넷판매 i
#   join 고객 c on c.고객키 = i.고객키
df_adw = pd.merge(df_sales, df_customer, on="고객키", how='inner')
df_adw.shape
import matplotlib.pyplot as plt
result = df_adw.groupby('성별')['판매금액'].sum()
result.plot(kind='bar')

df_adw['판매금액'].plot(kind='hist')

iris

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
iris = pd.read_csv('data/iris.csv')
x = iris.drop('variety',axis=1) # 열 삭제
y = iris['variety']
# 분류기 생성
clf = DecisionTreeClassifier(random_state=11)

# 학습
clf.fit(x,y)

# 예측 작업을 수행
pred = clf.predict(x)
pred

0개의 댓글