Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66063016/using-pass-in-if-statement-in-lambda-function-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...