简体   繁体   中英

using pass in if statement in lambda function python

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

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)

You can do

df.columns = df.columns.abs()

That should work.

apllying per column should do the job.

ie

df.columns = df.columns.abs()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM