I have a couple pandas data frame questions. I would like to replace the values in only certain cells (based on a boolean condition) with a value identified from another cell. I have defined the data frame from an imported text file, which returns a data frame with column headers 'P' and 'F' and values in all of the cells. I want to replace only those cells in column 'F' where the corresponding 'P' entry in the same row is less than a defined variable, Plithos. The new value for all of the replaced cells is defined as Fmax, which is the value of 'F' when 'P' in the same row == Plithos:

Plithos = 5.0

Fmax = df.loc[(df['P']==Plithos),'F']

The above part seems to work. The Fmax value returned is the correct one from the table. But when I try to replace the appropriate values using the code below, the right cells are identified but the new entries are all NaN:

df.loc[(df['P'] < Plithos),'F'] = Fmax

I'm not sure why this is happening, or what I should change in the syntax to fix it? Any help is appreciated!

Second question: Ideally, I would also like to define the condition for Fmax to be the value found in the row where P is equal to or less than Plithos, but the closest possible (so, the Price is Right match, I guess?). That way if the user input spreadsheet doesn't have a perfect matching value for Plithos in their table, the code still works. I assume pandas doesn't have a Price is Right boolean built in, though...

  • $\begingroup$ Take a look at numpy.where, you should be able to achieve what you're trying to do. $\endgroup$
    – Oxbowerce
    Jan 15, 2020 at 19:50

1 Answer 1


Aha! For some reason, when I named a variable that pointed to a value in a data frame, and then tried to use the variable to put it back into the table replacing other cells, it changed the data type. That's why I was getting NaNs. I just had to convert it to a usable type using tolist.

As for the nearest-value identification, this seems to have worked:

Pfinal = df.iloc[(df['P']-Plithos).abs().idxmin()]

F_max = Pfinal[1]

F_max = F_max.tolist()

df.loc[(df['P'] < Plithos),['F']] = F_max

Your Answer

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

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