Home > Blockchain >  Can I use a value stored in a variable after an if statement with the loc method?
Can I use a value stored in a variable after an if statement with the loc method?

Time:03-24

I created an if else statement to determine whether the min or max is the bigger difference and then stored the number to a variable.

findValue = 0.0

minAbs = abs(df[["numbers"]].min())
maxAbs = abs(df[["numbers"]].max())

if minAbs > maxAbs:
  findValue = minAbs
else:
  findValue = maxAbs

**df2=df.loc[df['numbers'] == findValue, 'day_related']**
df2

Python hates that I use findValue and not the actual number that it's set equal to in the statement with ** around it, but I thought these are interchangeable?

CodePudding user response:

df[["numbers"]] creates a new dataframe with one column called numbers, so df[["numbers"]].max() isn't actually going to return a number; it's going to return a Series object with one item. df["numbers"] will return the actual numbers column so .max() and .min() will work as expected.

Change your code to this:

minAbs = abs(df["numbers"].min())
maxAbs = abs(df["numbers"].max())

...and then the rest of your code.

  • Related