바뀜

둘러보기로 가기 검색하러 가기
잔글
96번째 줄: 96번째 줄:  
</syntaxhighlight>
 
</syntaxhighlight>
 
|}
 
|}
= mysql =
  −
데이터프레임을 SQL에 저장하기.
     −
mariasql도 동일하다.
+
= HTML =
 
+
웹문서에서 읽어온 데이터를 바로 dataframe화 하는 경우도 필요하다.
=== sqlalchemy 사용 ===
  −
이 방법은 굉장히 간단하다. 다만, 프라이머리키가 중복된 데이터가 있는 경우엔 적용할 수가 없다.(이런 경우엔 겹치는 데이터를 제거해준 후 넣어야 한다.)
   
{| class="wikitable"
 
{| class="wikitable"
!과정
+
! 의도
!설명
   
!방법
 
!방법
|-
  −
|라이브러리 설치
  −
|
  −
|pip install sqlalchemy
  −
|-
  −
|모듈 임포트
  −
|
  −
|from sqlalchemy import create_engine
  −
|-
  −
|엔진 연결
  −
|DB를 만든 후에 DB와 연결할 수 있다.
  −
|<syntaxhighlight lang="python">
  −
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
  −
                      .format(user="root",  # sql 계정 입력.
  −
                              domain='localhost',      # 도메인 주소
  −
                              pw="0000",  # sql 비밀번호 입력.
  −
                              db="dbname"))  # 연결할 db이름 입력.
  −
</syntaxhighlight>
  −
|-
  −
|sql로 전환
  −
|이미 만들어진 테이블에 dataframe을 넣는다.
  −
(역시, 테이블은 미리 준비되어야 한다.)
  −
  −
옵션은 아래에서 설명한다.
  −
|<syntaxhighlight lang="python">
  −
df.to_sql('테이블명', con = engine, if_exists = 'append', chunksize = 1000)
  −
</syntaxhighlight>
  −
|-
  −
|옵션값
  −
| colspan="2" |
  −
{| class="wikitable"
  −
!인자
  −
!설명
  −
|-
  −
|if_exists
  −
|
  −
{| class="wikitable"
  −
!옵션
   
!설명
 
!설명
 
|-
 
|-
|appends
+
|데이터 불러오기
|기존에 데이터가 들어가 있으면 덧붙인다.
+
|객체 = pandas.read_html('''h<nowiki/>t<nowiki/>ml 문서''')'''<nowiki/><nowiki/><nowiki/><nowiki/><nowiki/><nowiki/><nowiki/><nowiki/><nowiki/><nowiki/>'''
|-
+
|'''<nowiki/>'''html 문서의 데이터타입은 str이어야 한다. requests 등으로 웹문서를 불러와 변환해 넣으면 된다.'''<nowiki/><nowiki/><nowiki/>'''
|replace
+
|}표형 데이터는 쉽게 가져올 수 있다.<syntaxhighlight lang="python">
|기존의 데이터를 대체한다.(테이블 단위로 덮어씌워, 기존 데이터는 사라진다.)
+
page = requests.get(url)
(테이블 세팅도 바꾼다.)
+
tables = pd.read_html(page.text)
|-
+
</syntaxhighlight>  [굳이 .text 속성에 접근해야 하네;;? 그냥 객체와 text속성은 어떻게 다른지 보자.]
|fail
  −
|테이블 안에 데이터가 있으면 아무것도 하지 않음.
  −
|}
  −
|-
  −
|chunksize
  −
|한 번에 몇 개의 데이터를 처리할지.
  −
|}
  −
|}
  −
 
  −
==== 관련에러 ====
  −
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, "Access denied for user '.....'@'localhost' (using password: YES)")
  −
 
  −
위 형태의 에러는... 99% 확률로 DB에 대한 정보를 잘못 입력했기 때문에 나오는 에러이다.
     −
=== 단순 입력 ===
+
여러 테이블이 있는 경우, 데이터프레임이 들어있는 리스트로 반환된다.
중복된 데이터는 그냥 건너뛰고 새로운 값을 넣어주고 싶을 때 사용하는 방법이다.
  −
{| class="wikitable"
  −
!과정
  −
!설명
  −
!방법
  −
|-
  −
|라이브러리 설치
  −
|
  −
|pip install pymysql
  −
|-
  −
|모듈 임포트
  −
|
  −
|import pymysql
  −
|-
  −
|DB연결
  −
|
  −
|DB = pymysql.connect(host='localhost', port=3306, db='db이름', user="root", passwd='비밀번호', charset='utf8')
  −
|-
  −
|커서생성
  −
|sql을 순회하는 커서 생성
  −
|cur = self.coinDB.cursor()
  −
|-
  −
|함수제작
  −
|함수로 만들어 처리하면 편할 듯하다.
  −
DB 객체와 테이블명을 넣어 작동한다.
  −
|<syntaxhighlight lang="python">
  −
def df_to_db(df, db, table):
  −
    '''df를 받아 db에 저장하는 것.'''
  −
    cur = db.cursor()  # 커서를 만든다.
  −
    cols = "`,`".join([str(i) for i in df.columns.tolist()])  # df의 칼럼을 추출한다.
  −
    for i, row in df.iterrows():  # 하나씩 입력한다.
  −
        try:
  −
            sql = "INSERT INTO `{table}` (`{cols}`) VALUES (".format(table=table, cols=cols) +  "%s," * (
  −
                        len(row) - 1) + "%s)"  # 마지막엔 쉼표 없이.
  −
            cur.execute(sql, tuple(row))
  −
            # the connection is not autocommitted by default, so we must commit to save our changes
  −
            db.commit()
  −
        except Exception as e:
  −
            # print(e)
  −
            pass
  −
</syntaxhighlight>
  −
|}
  −
[[분류:Pandas:DataFrame]]
 

둘러보기 메뉴