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
user3225309
1,3934 gold badges20 silver badges34 bronze badges
1 Answer 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
Marc Yefimchuk
1112 silver badges8 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py