How can I print only rows that have a precise column number greater than x ? Sheets Api with Python

天涯浪子 提交于 2021-01-28 10:00:37

问题


So what I want to do is print only rows that have for example the price (or any other row "title" cell greater or equal to let's say 50.

I haven't been able to find the answer elsewhere and couldn't do it myself with the API documentation. I'm using Google Sheets API v4 and my goal is based on a sheets that contain information on mobile subscription, allow user to select what they want for price, GB, etc.

Here is what my sheets look like:

Also, here is an unofficial documentation which I found great even though it didn't contain the answer I need, maybe someone here would succeed?

I tried running the following code but it didn't work:

val_list = col5 

d = wks.findall(>50) if cell.value >50 :

print (val_list)

I hope you will be able to help me. I'm new to Python.


回答1:


I think you had the right idea, but it looks like findall is for strings or regex, not an arbitrary boolean condition. Also, some of the syntax is a bit off, but that's to be expected when you are just starting out.

Here is how I would approach this with just what I could find in your attached document. I doubt this is the fastest or cleanest way to do this, but I think it's at least conceptually clear:

#list of all values in 4th/price column
prices=wks.col_values(4) 
#Remove nonnumeric characters from prices
prices=[p.replace('*','') for p in prices[1:]]

#Get indices of rows with price >=50
##i+2 to account for one indexing and removing header row
indices=[i+2 for i,p in enumerate(prices) if float(p)>=50]
#Print these rows
for i in indices:
    row=wks.row_values(i)
    print(row)    

Going forward with this project, you may want to put these row values into a dataframe rather than just printing them so you can do further analysis on this subset of the data.



来源:https://stackoverflow.com/questions/64575010/how-can-i-print-only-rows-that-have-a-precise-column-number-greater-than-x-she

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!