mysql - joining a list and a list of lists in python -


i have should simple problem 3 hours trying different things , cant solve it.

i have pymysql returning me results query. cant share exact example straw man should do.

cur.execute("select name, address, phonenum contacts") 

this returns results grab with

results = cur.fetchall() 

and convert list object want it

data = list(results) 

unfortunately doesn't include header can cur.description (which contains metadata including not limited header). push list

header=[] n in cur.description:     header.append(str((n[0]))) 

so header looks like:

['name','address','phonenum'] 

and results like:

[['tom','dublin','12345'],['bob','kerry','56789']] 

i want create dataframe in pandas , pivot needs column headers work properly. had been importing completed csv pandas df included header worked smoothly need data direct db thinking, that's easy, join 2 lists , hey presto have looking for, when try append wind this:

['name','address','phonenum',['tom','dublin','12345'],['bob','kerry','56789']] 

when need this

[['name','address','phonenum'],['tom','dublin','12345'],['bob','kerry','56789']] 

anyone ideas? appreciated!

addition of lists concatenates contents:

in [17]: [1] + [2,3] out[17]: [1, 2, 3] 

this true if contents lists:

in [18]: [[1]] + [[2],[3]] out[18]: [[1], [2], [3]] 

so:

in [13]: header = ['name','address','phonenum']  in [14]: data = [['tom','dublin','12345'],['bob','kerry','56789']]  in [15]: [header] + data out[15]:  [['name', 'address', 'phonenum'],  ['tom', 'dublin', '12345'],  ['bob', 'kerry', '56789']]  in [16]: pd.dataframe(data, columns=header) out[16]:    name address phonenum 0  tom  dublin    12345 1  bob   kerry    56789 

note loading dataframe data database can done pandas.read_sql.


Comments