1

I want get a db into pandas df in Python. I use a following code:

self.cursor = self.connection.cursor()
query = """
        SELECT * FROM `an_visit` AS `visit`                 
        JOIN `an_ip` AS `ip`  ON  (`visit`.`ip_id` = `ip`.`ip_id`)
        JOIN `an_useragent` AS `useragent` ON (`visit`.`useragent_id` = `useragent`.`useragent_id`)                 
        JOIN `an_pageview` AS `pageview`  ON (`visit`.`visit_id` = `pageview`.`visit_id`)       
        WHERE `visit`.`visit_id` BETWEEN  %s AND %s
        """
self.cursor.execute(query, (start_id, end_id))

df = pd.DataFrame(self.cursor.fetchall())

This code works, but I want to get column names as well. I tried this question MySQL: Get column name or alias from query

but this did not work:

fields = map(lambda x: x[0], self.cursor.description)
result = [dict(zip(fields, row)) for row in self.cursor.fetchall()]

How can I get column names from db into df? Thanks

Shadow
  • 33,525
  • 10
  • 51
  • 64
vojtam
  • 1,157
  • 9
  • 34

4 Answers4

4

The easy way to include column names within recordset is to set dictionary=True as following:

self.cursor = self.connection.cursor(dictionary=True)

Then, all of fetch(), fetchall() and fetchone() are return dictionary with column name and data

check out links: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

https://mariadb-corporation.github.io/mariadb-connector-python/connection.html

Andy Z
  • 406
  • 3
  • 4
2

What work to me is:

field_names = [i[0] for i in self.cursor.description ]
vojtam
  • 1,157
  • 9
  • 34
0

There is a column_names properties in MySql cursor that you can use:

row = dict(zip(self.cursor.column_names, self.cursor.fetchone()))

https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html

Jayvee
  • 10,670
  • 3
  • 29
  • 40
0

the best practice to list all the columns in the database is to execute this query form the connection cursor

SELECT TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA='<schema>' AND TABLE_NAME = '<table_name>'
kiran kumar
  • 110
  • 4
  • ok, can you write it so it pass to my example above? I don`t know how to modify it to my case. – vojtam Dec 27 '21 at 10:11