pymysql-How to return the results of a query in the form of a list of tuples - pymysql

Lets say I have this code:
sql_query="select actor.actor_id from actor where actor='%s'"
cursor.execute=(sql_query,(actorID))
result=cursor.fetchall()
return(result)
What should I do to my code so the results are in the form of a list of tuples?Also I want the first tuple to be the name of the columns of my query.
For example: [(“Name”, “Id”,),(“Jim”,7,),(“Tom”,13,)]

Here is a sample example:
cur.execute('''SELECT * FROM patient_login''')
results = cur.fetchall()
nested_tuple_list = []
for result in results:
nested_tuple_list.append(result)
print(nested_tuple_list)
As you can see, we enter our select statement with cur.execute(). We fetch all of the results and store them in the variable results. We run a for loop, and each result will be a tuple of a result in our DB. We then append them to the end of the list. When we print the results, here is the output:
[(4, 'sikudabo', 'monkey1'), (83, 'sikudabo2', 'monkey2')]
We end up with a list of tuples.

Here is another answer that simple grabs the column names and stores them in a nested tuple:
cur.execute('''DESCRIBE patient_login''')
results = cur.fetchall()
nested_tuple_list = []
nested_tuple_list_2 = []
for result in results:
result = ((result[0]))
nested_tuple_list.append(result)
nested_tuple_list = tuple(nested_tuple_list)
nested_tuple_list_2.append(nested_tuple_list)
print(nested_tuple_list_2)
The describe command in SQL will Describe the table by telling you which columns exist within the table, and various characteristics of the table such as primary key, datatype ect. This command will return a tuple of the described data. Here we search each result and grab the first index in the results for each of the nested tuples. The first index corresponds with the column name in the for loop. We can append this to the first empty list. After we append all of the column names, we change the list to a tuple. We then append that tuple to the list and have all of the column names in the list within a tuple. Here is the output:
[('ID', 'username', 'password')]
If you want each element in the list to be a tuple in it of itself, here is the code:
nested_tuple_list = tuple(nested_tuple_list)
nested_tuple_list_2 = [(x,) for x in nested_tuple_list]
print(nested_tuple_list_2)
We can do a list comprehension with x representing each column, and here is our output for each of my columns in the DataFrame:
[('ID',), ('username',), ('password',)]

Related

How to create dataframe from ordered dictionary?

I have an ordered dictionary which has 4 keys and multiple values. I tried to create the dataframe like this
df = pd.DataFrame(items, index=[0])
print('\ndf is ',df)
But this triggers ValueError, as the multiple values from the dictionary don't match.
The ordered dictionary is below:
OrderedDict([('Product', 'DASXZSDASXZS'), ('Region', ['A', 'B', 'C']), ('Items', ['1', '2', '3']), ('Order', ['123', '456', '789'])])
I want the dataframe format to be like:
Product Region Items Order
DASXZSDASXZS A 1 123
DASXZSDASXZS B 2 456
...
How can I achieve this format for the dataframe?
Not enough rep to comment. Why do you try to specify index=[0]?
Simply doing
df = pd.DataFrame(items)
works; if you want to change the index, you can set it later with df.set_index(...)
#viktor_dmitry your comment to #Battleman links to external data, here's a solution.
In https://www.codepile.net/pile/GY336DYN you have a list of OrderedDict entries, in the example above you just had 1 OrderedDict. Each needs to be treated as a separate DataFrame construction. From the resulting list you use concat to get a final DataFrame:
ods = [OrderedDict([('MaterialNumber', '2XV9450-1AR24'), ('ForCountry'...]),
OrderedDict([('MaterialNumber', ...),
...]
new_df = pd.concat([pd.DataFrame(od) for od in ods])
# new_df has 4 columns and many rows
Note also that 1 of your example items is invalid, you'd need to filter this out, the rest appear to be fine:
ods[21]
OrderedDict([('MaterialNumber', '4MC9672')]) # lacks the rest of the columns!

Formula to sort by column that contains times and text, place text at the end, in Google Sheets

My Google Sheets Select statement selects rows from a master sheet of results and then sorts them by time (least amount of time first) ascending.
Some of these results will be entered as DNS and I want them to appear at the end of the time but they appear at the top.
Here is my statement:
Select A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,V,W where not D contains '/' and O is not Null order by P Asc
Column P contains time in HH:mm:ss formatted as duration. If one of the riders is a DNS, they appear at the top of the sort. Unless I sort descending - which is not desired.
With DNS, you probably mean "did not start". The query() function will only accept one data type in a column, and because most of the values in column P are time values, the "DNS" values will return as null. query() sorts null values first.
Try this to sort your data the way you describe:
=sort( { Data!A2:R, Data!Q2:R, Data!V2:W }, Data!P2:P, true )
Then use filter() or query() to remove rows where column D contains a /.

Simpler alternative to simultaneously Sort and Filter by column in Google Spreadsheets

I have a spreadsheet (here's a copy) with the following (headered) columns:
A: Indices for a list of groceries;
B: Names for the groceries to be indexed by column A;
C: Check column with "x" for inactive items in column B, empty otherwise;
D: Sorting indices that I want to apply to column B;
Currently, I am getting the sorted AND filtered result with this formula:
=SORT(FILTER(B2:B; C2:C = ""); FILTER(D2:D; C2:C = ""); TRUE)
The problem is that I need to apply the filter two times: one for the items and one for the indices, otherwise I get a mismatch between elements for the Sort function.
I feel that this doesn't scale well since it creates duplication.
Is there a way to get the same results with a simpler formula or another arrangement of columns?
=SORT(FILTER({Itens!B2:B\Itens!G2:G}; Itens!D2:D=""))
=SORT(FILTER({Itens!B2:B\Itens!G2:G}; Itens!D2:D="");2;1)
or maybe: =SORT(FILTER(Itens!B2:B; Itens!D2:D="");2;1)

Explode function returning single row

I used the field type as Array. "Select col as sample_table" returns the below output.
["[-80.86598534884,35.53423185253291],[-80.86598789514547,35.53423048990488],[-80.86598794307857,35.53423046392442]"]
When I used
select explode(col)
from sample_table.
I get the output as below which is a single row.
[-80.86598534884,35.53423185253291],[-80.86598789514547,35.53423048990488],[-80.86598794307857,35.53423046392442]
I want the output in 3 rows as below.
[-80.86598534884655,35.53423185253291]
[-80.86598789514547,35.53423048990488]
[-80.86598794307857,35.53423046392442]
As i see in the hive tutorial, explode function should return multiple rows but i don't see it happening
The input you have given appears as an array field having only one value. That entire value is taken as array of size one by explode function and thereby returns the result in a single row.

Linq comparing DataTable with List<String>

I have a string list (List) that contains delimited fields. An example would be:
List[0] = "7/1/2013,ABC,123456"
List[1] = "7/2/2013,DEF,234567"
I also have a DataTable where a record either will or will not contain the the values from the 2nd and 3rd column in the String List:
Example
Row[0][0]="ABC" <-----String
Row[0][1]=123456 <-----Int32
What I want to do is find any records (via Linq) in the DataTable that DO NOT have corresponding values in the String List.
I've been googling for a while, and can't quite find the right way to do this with Linq...can anyone help?
This code snippet should give you an enumeration of the indices that do not have the appropriate DataTable values:
var correspondingRecords =
from index in Enumerable.Range(0, List.Count)
let items = List[index].Split(',')
where !(item[1] == Row[index][0] && item[2] == Row[index][1])
select index;
The basic idea is to iterate over the indices in order to make sure that you're comparing the appropriate rows and list items to one another. Once you do that, it's simple enough to parse the list item and make the appropriate comparisons.

Resources