0

I have a dataframe and the function that I would like to apply:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
... 'A' : ['A1', 'A2', 'A3'],
... 'B' : ['B1', 'B2', 'B3'],
... 'format_str' : [None, np.nan, 'A = {A}, B = {B}']
... }
... )
>>> df
 A B format_str
0 A1 B1 None
1 A2 B2 NaN
2 A3 B3 A = {A}, B = {B}
>>> def gen_format_str(ser):
... if pd.isna(ser.format_str):
... return ser.A
... else:
... # return ser.format_str.format(A = ser.A, B=ser.B)
... return ser.format_str.format(**ser)
...
>>> df['new_field'] = df.apply(
... gen_format_str, axis=1
... )
>>> df
 A B format_str new_field
0 A1 B1 None A1
1 A2 B2 NaN A2
2 A3 B3 A = {A}, B = {B} A = A3, B = B3
>>>

Everything works as it should, but I would like to use lambda function instead of gen_format_str. I tried different approaches, but none of them worked.

How to implement the same functionality of gen_format_str by using lambda function in apply method?

Regards.

asked Apr 16, 2020 at 14:48

1 Answer 1

1

This seems to be doing the job :

df['new_field'] = df.apply(
 lambda ser: ser.A if pd.isna(ser.format_str) else ser.format_str.format(**ser), 
 axis=1 
)
answered Apr 16, 2020 at 15:05
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.