programing

MySQL 데이터베이스에서 열 이름을 포함한 Panda 데이터 프레임으로 데이터 가져오기

goodjava 2022. 11. 5. 17:46

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