Search code examples
pythonimpalatabulate

Tabulating data coming from a DB query


I feel I'm either not searching for the correct terms or I'm not fully understanding the difference in how data is 'constructed' in Python compared to say, SAS or SQL.

I've connected PyCharm Pro to an Impala database. I'm able to query a table and it returns in format:

('Ford', 'Focus 2dr', 'column3data', 'column4data', 'etc')

I'm limiting my SQL query for now, just grabbing the first two columns, and I'm printing this into tabulate. The problem is, all tabulate is doing is putting that entire row into a single cell.

print(tabulate([records], headers=["make", "model"]))

I can see why if I just print the [records] as it's just a long string, but how do I get tabulate to treat the data properly and split the records into their respective columns?


Solution

  • You have to split that set into chunks of length that matches the number of columns.

    For example:

    from tabulate import tabulate
    
    your_sample_query = ('Ford', 'Focus 2dr', 'column3data', 'column4data', 'etc')
    chop_it = [your_sample_query[i:i+2] for i in range(0, len(your_sample_query), 2)]
    print(tabulate(chop_it, headers=["make", "model"], tablefmt="sql"))
    
    

    This outputs:

    make         model
    -----------  -----------
    Ford         Focus 2dr
    column3data  column4data
    etc