# Conditionally replace dataframe cells with value from another cell

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...

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

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.
Pfinal = df.iloc[(df['P']-Plithos).abs().idxmin()]