PyQt4 - QTableView - How to loop over QTableView - python

I tried to find an example in python where I can loop over model elements of a QTableView and print the entire row.
I have found how to loop over selected rows but nothing when rows are not selected.
Can someone help me? No need to tell me how to create the model and how to apply it to the QTableModel. I am only interested how to iterate over the rows.

I think you confused model and view in some places within your question...
But, why not simply get the number of rows and columns and loop over all of them:
for irow in xrange(model.rowCount()):
row = []
for icol in xrange(model.columnCount()):
cell = model.data(model.createIndex(irow, icol))
row.append(cell)
# print all elems per row
print ', '.join(str(c) for c in row))
Things can probably be beautified and/or written in a more compact way, but that's basically all.
Or am I missing something?

Related

An efficient way to fill a dearpygui table using pandas

For now, I just make each column in to a list df['Name'].to_list() -> zip(list1,list2 ,....) all the lists, and iterate over them and then I add them in the table.
I would imagine this is far from an ideal solution. Is there anything better to fill the dearpygui table while using pandas?
I don't know much about your approach but here is a generalized example of what i use:
dataset = pd.read_csv(filename) # Take your df from wherever
with dpg.table(label='DatasetTable'):
for i in range(dataset.shape[1]): # Generates the correct amount of columns
dpg.add_table_column(label=dataset.columns[i]) # Adds the headers
for i in range(n): # Shows the first n rows
with dpg.table_row():
for j in range(dataset.shape[1]):
dpg.add_text(f"{dataset.iloc[i,j]}") # Displays the value of
# each row/column combination
I hope it can be useful to someone.

Printing and counting unique values from an .xlsx file

I'm fairly new to Python and still learning the ropes, so I need help with a step by step program without using any functions. I understand how to count through an unknown column range and output the quantity. However, for this program, I'm trying to loop through a column, picking out unique numbers and counting its frequency.
So I have an excel file with random numbers down column A. I only put in 20 numbers but let's pretend the range is unknown. How would I go about extracting the unique numbers and inputting them into a separate column along with how many times they appeared in the list?
I'm not really sure how to go about this. :/
unique = 1
while xw.Range((unique,1)).value != None:
frequency = 0
if unique != unique: break
quantity += 1
"end"
I presume as you can't use functions this may be homework...so, high level:
You could first go through the column and then put all the values in a list?
Secondly take the first value from the list and go through the rest of the list - is it in there? If so then it is not unique. Now remove the value where you have found the duplicate from the list. Keep going if you find another remove that too.
Take the second value and so on?
You would just need list comprehension, some loops and perhaps .pop()
Using pandas library would be the easiest way to do. I created a sample excel sheet having only one column called "Random_num"
import pandas
data = pandas.read_excel("sample.xlsx", sheet_name = "Sheet1")
print(data.head()) # This would give you a sneak peek of your data
print(data['Random_num'].value_counts()) # This would solve the problem you asked for
# Make sure to pass your column name within the quotation marks
#eg: data['your_column'].value_counts()
Thanks

Cannot find way to iterate two ways in for loop while using operations on pandas?

So I'm trying to calculate the manhattan distance between a query and a dataframe called data.
The code below is what I have so far, and in terms of the calculations, it does the right thing. The problem is that I have tried and tried to find a way to get it to iterate also through the column names to avoid all of this repetition of code through columns such as LIFE_EXP etc.
How can I optimize this for loop?
My other query is about getting it into a form where I can have pairs of values i.e country name and output, so that I can sort by the output values?
Help please, I am very new to python!
list = []
for row in range(len(data)):
list.append((data['COUNTRY_ID'][row], abs(query['LIFE_EXP'].sub(data['LIFE_EXP'][row])) + abs(query['TOP10_INCOME'].sub(data['TOP10_INCOME'][row])) + abs(query['INFANT_MORT'].sub(data['INFANT_MORT'][row])) +abs(query['MIL_SPEND'].sub(data['MIL_SPEND'][row])) +abs(query['SCHOOL_YEARS'].sub(data['SCHOOL_YEARS'][row]))))
Since pandas supports the plus operator, you can use the sum function:
list = []
column_list = ['LIFE_EXP', 'TOP10_INCOME', 'INFANT_MORT', 'MIL_SPEND', 'SCHOOL_YEARS']
for row in range(len(data)):
list.append((data['COUNTRY_ID'][row], sum([abs(query[col].sub(data[col][row])) for col in column_list])))

Python - Trying to read a csv file and output values with specific criteria

I am going to start off with stating I am very much new at working in Python. I have a very rudimentary knowledge of SQL but this is my first go 'round with Python. I have a csv file of customer related data and I need to output the records of customers who have spent more than $1000. I was also given this starter code:
import csv
import re
data = []
with open('customerData.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
print(data[0])
print(data[1]["Name"])
print(data[2]["Spent Past 30 Days"])
I am not looking for anyone to give me the answer, but maybe nudge me in the right direction. I know that it has opened the file to read and created a list (data) and is ready to output the values of the first and second row. I am stuck trying to figure out how to call out the column value without limiting it to a specific row number. Do I need to make another list for columns? Do I need to create a loop to output each record that meets the > 1000 criteria? Any advice would be much appreciated.
To get a particular column you could use a for loop. I'm not sure exactly what you're wanting to do with it, but this might be a good place to start.
for i in range(0,len(data)):
print data[i]['Name']
len(data) should equal the number of rows, thus iterating through the entire column
The sample code does not give away the secret of data structure. It looks like maybe a list of dicts. Which does not make much sense, so I'll guess how data is organized. Assuming data is a list of lists you can get at a column with a list comprehension:
data = [['Name','Spent Past 30 Days'],['Ernie',890],['Bert',1200]]
spent_column = [row[1] for row in data]
print(spent_column) # prints: ['Spent Past 30 Days', 890, 1200]
But you will probably want to know who is a big spender so maybe you should return the names:
data = [['Name','Spent Past 30 Days'],['Ernie',890],['Bert',1200]]
spent_names = [row[0] for row in data[1:] if int(row[1])>1000]
print(spent_names) # prints: ['Bert']
If the examples are unclear I suggest you read up on list comprehensions; they are awesome :)
You can do all of the above with regular for-loops as well.

Updating rows in a SQLite database using Python

I have the following problem:
I want to update an existing SQLite database row by row. What's happening now is that the iterator updates all existing rows with the last assigned value of dbdata.
I don't want that.
I want update row 1 with the first assigned value of dbdata. Then take iterator shall go "up" again, get the next value and the updating should go on to the next row.
Obviously there is a problem with the logic but I cannot get my head around it.
Whats happening now is that the rows are updated now which leaves me with the last assigned value of dbdatafor all rows. I only want one row to be updated per iteration.
How do I tell Python to always "go one row down"? Can someone give a hint? I am not looking for a complete solution here. My current code is as follows:
for row in dbconnector:
print (row)
dbdata = langid.classify("{}".format(row))
print (dbdata)
connector.execute('''update SOMEDB set test1=? , test2=?''',(dbdata[-2], dbdata[-1]))
I am working with a SQLite Database and Python 3.3.
The reason all your data is set to the last dbdata is because your update isn't restricted to a single row so on each iteration all the rows are set to whatever dbdata you just processed. To restrict your update use a where clause so the only row affected is the one you want.
Solved it. Thanks for all the input!
n = 0
for row in dbconnector:
print (row)
dbdata = langid.classify("{}".format(row))
print (dbdata)
for amount in row:
n += 1
print (n)
connector.execute('''update SOMEDB set test1=? , test2=? where rowid == ?''',(dbdata[-2], dbdata[-1], n))
That works! It alters with every iteration the number of the rowid.

Categories