반응형

파이썬에서도 객체지향 프로그래밍(OOP) 의 중요성과 코딩 습관을 강조하곤 합니다.

클래스 내에 메소드를 구현할 때 파이썬에서는 3가지 유형을 제공합니다.

class method, intance method, static method 인데요.

 

아래 3가지 유형을 정리해봅니다.

 

- class method
    - 클래스에 바인딩되는 함수
    - 클래스의 상태를 수정하여 모든 인스턴스에 적용될 수 있는 함수
- instance method
    - self 를 첫 번째 인자로 받는 메소드
    - 클래스의 인스턴스를 “암시적”으로 입력받아 클래스 속성과 상호 작용할 수 있습니다.
    - 인스턴스 내  데이터를 액세스 할 수 있고, 수정할 수 있습니다.
- static method
    - 데코레이터를 이용해 정의합니다. 
    - 클래스의 인스턴스가 아닌 클래스에 속합니다.
    - 특정 클래스의 컨텍스트 내에서 의미가 있는  함수를 만들 때 정의합니다.

 

 

이중에서 class method 를 유틸리티 성 함수를 구현할 때 사용하면 좋은데요. 아래 예를 들어보겠습니다.

import pandas as pd
class DataETLProcessor:
    def __init__(self,data):
        self.data =data

    def process_etl(self):
        #write etl process logic code
        pass

    def from_csv_by_instance_method(self,filepath):
        self.data = pd.read_csv(filepath)

    @classmethod
    def from_csv_by_class_method(cls,filepath):
        data = pd.read_csv(filepath)
        return cls(data)

    @classmethod
    def from_json(cls,filepath):
        data = pd.read_json(filepath)
        return cls(data)
    
# case 1 실행 예제)
etl = DataETLProcessor()
etl.from_csv_by_instance_method("./sample_data.csv")
etl.process_etl()

# case 2실행 예제)
etl = DataETLProcessor.from_csv_by_class_method("./sample_data.csv")
etl.process_etl()

 

 

case 1는 instance method 를 이용한 호출이고, case2 는 class method 를 이용한 호출인데, 한 줄 줄었지만 더 간결해졌어요.

그리고 instance 와 class 관련된 변수와 기능, 로직을 분리하면 코드가 깔끔해집니다. 위에서 from_json , from_parquet 그리고 아예 파경로에서 파일 타입을 읽어 포맷별로 데이터를 읽을 수 있도록 구현할 수도 있구요.

 

프로그램의 볼륨이 커질수 있다면 유지보수 용이하게 저렇게 분리해서 구현하는 습관을 들여도 좋겠습니다.

 

물론 간단한 프로그램이라면 그냥 편한대로 구현하는게 더 좋을 수 있습니다.

반응형
반응형

pandas란?

  • 데이터 분석을 위한 파이썬 라이브러리
  • 행과 열로 이루어진 데이터 구조를 다룬다.
  • Series 와 Dataframe 자료구조를 사용한다.

 

 

Dataframe 생성

import pandas as pd

#테스트 데이터 dict 생성
data_exam = {
    'name':['a','b','c','d','e'],
    'height':[160,170,180,185,190],
    'age':[23,15,18,19,25],
    'class':['A','B','A','B','A']
}
.
#pandas dataframe 
df=pd.DataFrame(data_exam)

#read from csv file
df=pandas.read_csv(filepath,names=cols,header=None,encoding="cp949")


#Dataframe()으로 호출하면 안되니까 타이핑에 주의하자

df.index
df.columns
df.dtypes

 

Dataframe 다루기

> 특정 컬럼 조회
df['id'] 

> 특정 복수 컬럼 조회.
df[['id','age']] 

> where 절 조건 조회

df[('id'>10)] # ID 10이상만 조회

df.where(filter1 & filter2, inplace = True)


>컬럼 이름 변경
df.rename(columns={'oldName':'newName'},inplace=True)


>Dataframe convert to tuple
tmp = df['id']
mytuple = [x for x in tmp.to_numpy()]

> 컬럭 삭제
df = df.drop(['컬럼이름','col2'],axis=1)
df.dropna(subset=['컬럼이름'],inplace=True)


> 데이터 컬럼 값 변경
df['Gender'].replace('male',1) # Gender 컬럼의 male 값을 1로 대체
df.loc[df['Gender']=='male','Gender']=1



> 특정 컬럼이 널값인 경우 조회
df[df['컬럼1'].isnull()]


> where, query
dt.where(dt.컬럼명1 == 'value').count()['id']

dt.query('컬럼명1 == "value" | 컬럼명2 > 5').count()


> Group By 
dt.groupby('class') #집계할 컬럼
.agg({'height':['count','mean']}) #집계 함수를 적용
.sort_values([('height','mean')]) # 정렬

#agg 에 컬럼 이름을 주면 multiIndex로 생성되는데 () set 형태로 컬럼 이름이 생성된다.


dt.groupby('컬럼이름').size()  그룹별 카운트


> merge

merge_view=view.merge(user,on='uid').merge(product,on='pid')
merge_view=view.merge(user,on='uid').merge(product,on='pid',how='outer')

 

 

Parquet 파일을 Pandas DataFrame 으로 로드하기

rom fastparquet import ParquetFile

# 만약 압축을 풀어야 한다면
import snappy
def snappy_decompress(data, uncompressed_size):
    return snappy.decompress(data)


pf = ParquetFile('sample.snappy.parquet') # filename includes .snappy.parquet extension
df=pf.to_pandas()
pf = ParquetFile('/Users/amore/178309483_20220714_0000_000000000000.parquet')

## 2
df=pd.read_parquet('/Users/amore/appsflyer.snappy.parquet')
df.head()
print(df.head())

 

MySQL 테이블로부터  Pandas DataFrame 으로 로드하기

from sqlalchemy import create_engine
import pandas as pd
import pymysql



db_conn_str = 'mysql+pymysql://User:비밀번호@DB호스트'
mysql_conn = create_engine(db_conn_str)


data = pd.read_sql_table('BOT_USER',mysql_conn)
 
반응형
반응형

1.streamlit 이란?

파이썬 웹 프레임워크 라이브러리

데이터 사이언스와 머신러닝에 유용한 커스텀 웹 앱을 쉽게 만들어 줄 수 있다고 한다.

시각화와 차트 제공을 위한 다양한 서드파티 모듈이 있다

참고) 공공 데이터  https://www.data.go.kr/index.do

2. 왜 streamlit 을 선택할까 ?

아직 잘은 모르겠지만 내가 봤을때, 데이터 레포트를 웹 페이지로 만들고 싶은데 웹 서버 구축에 대한 부담 없이 텍스트와 마크다운 수준의 코드 만으로 띄우고 싶을때 쓰면 좋을 것 같다.

 

3. streamlit 따라 해보기

a. lib 설치

$ pip install streamlit

 

 

b. app 코드 작성하기

# import module
import streamlit as st
import pandas as pd

# Title
st.title("This is Title line")

# Header
st.header("This is a header")

st.text("This line belongs to a text")



# Markdowns
st.markdown("### This is a markdown")
st.markdown("## This is a markdown")
st.markdown("# This is a markdown")

#Select the subject from the Selectbox
subject = st.selectbox("Subjects: ",['English', 'Hindi', 'Math',
                       'Science'])
# Print the subject
st.write("Your Subject is: ", subject)



# Reading the CSV file
df = pd.read_csv("Startups_Expense.csv")
# Putting title
st.title("View of the Data shown below:")
# To visualize the data
st.write(df)

 

 

c. 실행하기

$ streamlit run app.py

 

 

 

 

d. 그 외 컴포넌트를 알아보려면?

https://streamlit.io/components

 

Components • Streamlit

Streamlit is an open-source Python framework for machine learning and data science teams. Create interactive data apps in minutes.

streamlit.io

 

반응형

+ Recent posts