주 메뉴 열기
대문
임의의 문서로
로그인
설정
Pywiki 소개
면책 조항
Pywiki
검색
바뀜
← 이전 편집
다음 편집 →
Pandas:DataFrame:다른 형태로 저장하고 불러오기
(편집)
2021년 9월 23일 (목) 14:05 판
731 바이트 추가됨
,
2021년 9월 23일 (목) 14:05
→단순 입력
89번째 줄:
89번째 줄:
|함수제작
|함수제작
|함수로 만들어 처리하면 편할 듯하다.
|함수로 만들어 처리하면 편할 듯하다.
+
DB 객체와 테이블명을 넣어 작동한다.
|<syntaxhighlight lang="python">
|<syntaxhighlight lang="python">
−
def df_to_db(df, 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
</syntaxhighlight>
</syntaxhighlight>
|}
|}
[[분류:Pandas:DataFrame]]
[[분류:Pandas:DataFrame]]
Sam
사무관
,
인터페이스 관리자
,
관리자
, 교사
편집
1,408
번