Search code examples
pythonpython-3.xcellgspread

How to get cell's coordinates by it's content python3?


So i have a problem, that i need to get the cell's coordinates (in google-sheets) by it's content, for example a have a cell that has "hello" in it's self, and a have some amount of other cell's. For example "world" and i know that "hello" is in column 4 (there is only 1 hello in the example), how do i get it's coordinates on python 3, please help! here is how it lookes like in google-sheets : here is how it lookes like in google-sheets.

Please give me a code that will make this in my understanding:

if "hello" in sheet.col_values(4):

print(coordinates of "hello")


Solution

  • How I approached your question:

    1. Since I have an excel sheet or csv file, I am going to "read" it via pandas and convert it to a pandas dataframe:
    import pandas as pd
    df = pd.read_csv('path/to/file', header=None) #if your file is .csv
    df = pd.read_excel('path/to/file', header=None) #if your file is .xlsx
    
    1. Pandas Dataframe provide the iloc property: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html

    Python lists are 0-based. So if I want an element that is located in my dataframe at 7th row /4th column, I will be able to get it like this:

    df.iloc[6, 3]
    
    1. Use a for loop to iterate over the total number of dataframe rows:
    for i in range(0, len(df)):
        if df.iloc[i, 3] == 'hello':
            print(i, 3)