I'm very new to pandas and I'm trying to implement the code to search for something on an excel spreadsheet.

Basically, the most recent price can be found on the furthest right column named "final cost", and that's what I need. However, there are multiple columns named "final cost" (as every invoice is posted on there).

What I currently have:

def find_most_recent(row_num: int, df) -> float:
    k = -1
    checker = False
    while not checker:
        if df.columns[k] == "final cost":
            if not pd.isnull(df.iloc[row_num, k]):
                checker = True
                return df.loc[row_num, df.columns[k]]
        k -= 1

where row_num is the current row that is being searched, and df is the current dataframe being searched.

However, this gets only the first encounter of "final cost". For example, on a dataset of:

enter image description here

I want the return to be one of the prices in column L, but I'm getting returns of values from column F instead.

Any suggestions of a method to use?


1 Answer 1


Found the answer, putting

if "final cost" in df.columns[k]:

instead of

if df.columns[k] = "final cost":

seemed to have fix it

  • 1
    $\begingroup$ Best possible route for an answer! $\endgroup$ Sep 3, 2019 at 19:04
  • 1
    $\begingroup$ Also, nicely written function. $\endgroup$ Sep 3, 2019 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.