Pandas:DataFrame:DataBase
둘러보기로 가기
검색하러 가기
판다스에 관한 정보들을 틀:Pandas:DataFrame을 통해 체계화하여 관리한다.
- Pandas:DataFrame:개요
- Pandas:DataFrame:구조 파악
- Pandas:DataFrame:구조 조작
- Pandas:DataFrame:다른 형태로 저장하고 불러오기
- Pandas:DataFrame:활용
- Pandas:DataFrame:관련 에러
1 개요[편집 | 원본 편집]
데이터프레임을 DB에 저장하거나, DB를 데이터프레임화 하여 가져오거나.
2 MySQL[편집 | 원본 편집]
데이터프레임을 SQL에 저장하기.
mariasql도 동일하다.
2.1 DataFram을 바로 DB에[편집 | 원본 편집]
2.1.1 sqlalchemy 사용[편집 | 원본 편집]
이 방법은 굉장히 간단하다. 다만, 프라이머리키가 중복된 데이터가 있는 경우엔 적용할 수가 없다.(이런 경우엔 겹치는 데이터를 제거해준 후 넣어야 한다.)
과정 | 설명 | 방법 | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
라이브러리 설치 | pip install sqlalchemy | |||||||||||||||
모듈 임포트 | from sqlalchemy import create_engine | |||||||||||||||
엔진 연결 | DB를 만든 후에 DB와 연결할 수 있다. | engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="root", # sql 계정 입력.
domain='localhost', # 도메인 주소
pw="0000", # sql 비밀번호 입력.
db="dbname")) # 연결할 db이름 입력.
| ||||||||||||||
sql로 전환 | 이미 만들어진 테이블에 dataframe을 넣는다.
(역시, 테이블은 미리 준비되어야 한다.) 옵션은 아래에서 설명한다. |
df.to_sql('테이블명', con = engine, if_exists = 'append', chunksize = 1000)
| ||||||||||||||
옵션값 |
|
2.1.1.1 관련에러[편집 | 원본 편집]
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, "Access denied for user '.....'@'localhost' (using password: YES)")
위 형태의 에러는... 99% 확률로 DB에 대한 정보를 잘못 입력했기 때문에 나오는 에러이다.
2.2 새로운 값 갱신[편집 | 원본 편집]
중복된 데이터는 그냥 건너뛰고 새로운 값을 넣어주고 싶을 때 사용하는 방법이다.
과정 | 설명 | 방법 |
---|---|---|
라이브러리 설치 | 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 객체와 테이블명을 넣어 작동한다. |
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
|