1

I have a df in pandas, python with mostly float values but contains a few strings and looks as such:

index  cashflow    date          changeinvalue
0      5000        2019-12-31    9300  
1      4000        2019-12-31    -4000  
2      -2000       2019-12-31    -9000  

I am trying to use an apply function and lambda function to turn all values in the dataframe to absolute values. However I think I may be using the lambda function incorrectly as using the following code I get the following error:

df.apply(lambda x: abs(x) if isinstance(x, str) == False else pass)

SyntaxError: invalid syntax

Would anyone be able to help me? Thanks

3 Answers 3

1

Select only numeric columns by DataFrame.select_dtypes and convert them to absolute values:

cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].abs()
print (df)
       cashflow        date  changeinvalue
index                                     
0          5000  2019-12-31           9300
1          4000  2019-12-31           4000
2          2000  2019-12-31           9000

Your solution failed, because need test elementwise, not by columns in apply.

So if need test each value separately use DataFrame.applymap, then test numeric int and float for absolute values and all another values not change (so return back):

df = df.applymap(lambda x: abs(x) if isinstance(x, (int, float)) else x)
Sign up to request clarification or add additional context in comments.

1 Comment

It might be worth mentioning why the OP's code errored. The pass issue.
0

You can do

df.columns = df.columns.abs()

That should work.

Comments

0

apllying per column should do the job.

i.e.

df.columns = df.columns.abs()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.