I am working with a QTableView and trying to retrieve values from the selected row(s). At other times I will be working with mulitiple rows using:
self.tableView5.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
The code below works, but only when the first row is selected. However, it shows:
identity[row].append(str(self.table_model5.data(index)))
IndexError: list index out of range
when another row is clicked.
names = []
emails = []
identity = []
data = sorted(set(index.row() for index in self.tableView5.selectionModel().selectedRows()))
for row in data:
identity.append([])
for column in range(0,2):
index = self.table_model5.index(row, column)
identity[row].append(str(self.table_model5.data(index)))
for item in identity:
names.append(item[0])
emails.append(item[1])
for name, recipient in zip(names, emails):
print(name, recipient)
The problem here is caused by the convoluted method you are using to populate the lists of values. I would suggest the following simplification:
names = []
emails = []
identity = []
for index in sorted(self.tableView5.selectionModel().selectedRows()):
row = index.row()
name = self.table_model5.data(self.table_model5.index(row, 0))
email = self.table_model5.data(self.table_model5.index(row, 1))
identity.append((name, email))
names.append(name)
emails.append(email)
Note that there is no need to use set, because selectedRows only returns one index per selected row.
It's identity[row] that throws this exceptions. Imagine you selected from the table rows 2 and 3. Then in the first iteration of your for row in data: loop the value of row will be 2 while your identity list will be one element long at that time.
Debug and fix your logic.
Related
I want to get an individual row from the QueryJob in BQ. My query: select count(*) from ... returns a single row & I want to read the count value which is its first column. So if I can get the first row then I can do row[0] for the first column. I can iterate: row in queryJob but since I require only the first row this seems unneccesary.
Below is what I've tried:
row = self.client.query(count_query)
count = row.result()[0]
This gives an error:
'QueryJob' object is not subscriptable"
How can I get individual rows from queryJob by the row index?
Just do:
row = self.client.query(count_query)
result = row.result().total_rows
This will give the count from the query
you can use to_dataframe():
result = self.client.query(count_query).to_dataframe()
#if you want to result as a integer:
result = self.client.query(count_query).to_dataframe()['first_column_name'].iat[0]
My dataset looks like this
Using python and pandas I want to display the count of each unique item in the coverage column which are stored in a list shown in the table.
I want to display that count by device and by date.
Example out put would be:
the unique coverage count being the count of each unique list value in the "coverage" row
You can use apply method to iterate over rows and apply a custom function. This function may return the length of the list. For example:
df["covarage_count"] = df["coverage"].apply(lambda x: len(x))
Here's how I solved it using for loops
coverage_list = []
for item in list(df["coverage"]):
if item == '[]':
item = ''
else:
item = list(item.split(","))
coverage_list.append(len(item))
# print(len(item))
df["coverage_count"] = coverage_list
I have this code written, but right now it's hardcoded with a specific index. I want to go through a dataframe and for each individual index in the list, I want to get the sum
sums = []
test = []
for index, row in df.iterrows():
if row['subject_id'] == subject_id_list[0]:
test.append(row['answer'])
test = list(map(int, test))
test_sum = sum(test)
sums.append(test_sum)
if there are 5 subjects in the list, I want the sum for each subject and put into a new list of all the sums
Could you add another for loop? Something like,
for index, row in df.iterrows():
for item in subject_id_list:
if row['subject_id'] == item:
test.append(row['answer'])
test_sum = sum(test)
sums.append(test_sum)
I am new in here and want to ask something about removing duplicate data enter, right now I'm still doing my project about face recognition and stuck in remove duplicate data enter that I send to google sheets, this is the code that I use:
if(confidence <100):
id = names[id]
confidence = "{0}%".format (round(100-confidence))
row = (id,datetime.datetime,now().strftime('%Y-%m-%d %H:%M:%S'))
index = 2
sheet.insert_row (row,index)
data = sheet.get_all_records()
result = list(set(data))
print (result)
The message error "unhashable type: 'dict"
I want to post the result in google sheet only once enter
You can't add dictionaries to sets.
What you can do is add the dictionary items to the set. You can cast this to a list of tuples like so:
s = set(tuple(data.items()))
If you need to convert this back to a dictionary after, you can do:
for t in s:
new_dict = dict(t)
According to documentation of gspread get_all_records() returns list of dicts where dict has head row as key and value as cell value. So, you need to iterate through this list compare your ids to find and remove repeating items. Sample code:
visited = []
filtered = []
for row in data:
if row['id'] not in visited:
visited.append(row['id'])
else:
filtered.append(row)
Now, filtered should contain unique items. But instead of id you should put the name of the column which contains repeating value.
I want to read a row from an excel sheet based on the user input. My excel sheet contains columns with number, priority, assignee and other details.
Eg:- if I want to fetch the entire row of data for number= PRB00000, I am currently doing that with the below code. I am using a list and manually finding the index of it and hard-coding it to a VARIABLE and then sending it to selenium webdriver eg:- webelement.send_keys(variable). I don't want to do that and instead read the row based on user input and store the values in respective columns names.
book=xlrd.open_workbook('C:\\xxxx\\xxxx\\third party power.xlsx')
#print (book.nsheets)
#print (book.sheet_names())
first_sheet=book.sheet_by_index(0)
prb= "PRB0045087"
list1 = []
for sheet in book.sheets():
for rowidx in range(sheet.nrows):
row=sheet.row(rowidx)
for colidx, cell in enumerate(row):
if cell.value == prb :
list1 = first_sheet.row_values(rowidx)
RCA = list1[20]
LTF = list1[21]
Suggest you do a dictionary of IDs and row index, that way you can look it up
ids = {cell.value:colidx for colidx,cell in enumerate(row)}