MySQL 데이터베이스에서 열 이름을 포함한 Panda 데이터 프레임으로 데이터 가져오기
MySQL 데이터베이스에서 Panda 데이터 프레임으로 데이터를 Import합니다.사용하고 있는 코드는 다음과 같습니다.
import mysql.connector as sql
import pandas as pd
db_connection = sql.connect(host='hostname', database='db_name', user='username', password='password')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table_name')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
데이터 프레임을 인쇄하면 데이터가 올바르게 표시되지만, 열 이름도 유지할 수 있습니까?다음으로 출력 예를 나타냅니다.
0 1 2 3 4 5 6 7 8
0 :ID[giA0CqQcx+(9kbuSKV== NaN NaN None None None None None None
1 lXB+jIS)DN!CXmj>0(P8^]== NaN NaN None None None None None None
2 lXB+jIS)DN!CXmj>0(P8^]== NaN NaN None None None None None None
3 lXB+jIS)DN!CXmj>0(P8^]== NaN NaN None None None None None None
4 lXB+jIS)DN!CXmj>0(P8^]== NaN NaN None None None None None None
저는 판다 기둥 인덱스를 대체할 기둥 이름을 유지하고 싶습니다.예를 들어 열 이름은 0 대신 MySQL 테이블에서와 같이 "First_column"이 됩니다.이 문제를 해결할 좋은 방법이 있나요?아니면 MySQL에서 Panda 데이터 프레임으로 데이터를 가져오는 방법이 저보다 더 효율적인 방법이 있을까요?
IMO는 MySQL 서버에서 데이터를 읽을 때 Panda를 사용하는 것이 훨씬 효율적입니다.
from sqlalchemy import create_engine
import pandas as pd
db_connection_str = 'mysql+pymysql://mysql_user:mysql_password@mysql_host/mysql_db'
db_connection = create_engine(db_connection_str)
df = pd.read_sql('SELECT * FROM table_name', con=db_connection)
열 이름도 처리해야 합니다.
언급URL : https://stackoverflow.com/questions/37730243/importing-data-from-a-mysql-database-into-a-pandas-data-frame-including-column-n
'programing' 카테고리의 다른 글
| php에서 다중 파일 업로드 (0) | 2022.11.05 |
|---|---|
| 봄에 스케줄된 작업을 조건부로 활성화 또는 비활성화하려면 어떻게 해야 합니까? (0) | 2022.11.05 |
| 테이블의 일부에 대해 mysqldump를 사용하는 방법 (0) | 2022.11.05 |
| 내부 또는 외부 명령으로 인식되지 않습니다. (0) | 2022.11.02 |
| 테스트 클래스에 대해서만 비공개 방법을 공개하기 위한 주석 (0) | 2022.11.02 |