0

I know how to apply an IF condition in Pandas DataFrame. link

However, my question is how to do the following:

if (df[df['col1'] == 0]):
   sys.path.append("/desktop/folder/")
   import self_module as sm
   df = sm.call_function(df)

What I really want to do is when value in col1 equals to 0 then call function call_function().

def call_function(ds):
   ds['new_age'] = (ds['age']* 0.012345678901).round(12)
   return ds

I provide a simple example above for call_function().

2
  • Just curious, why are you reassign df = sm.call_function(df)? Do you mean df = sm.call_function(df[df['col1']== 0]), that is, to transform only part of the data? Commented Oct 28, 2020 at 20:59
  • I want to do the whole data for call_function() if df['col1']== 0, for those not equal to 0, leave pd.NaT. Commented Oct 28, 2020 at 21:06

1 Answer 1

1

Since your function interacts with multiple columns and returns a whole data frame, run conditional logic inside the method:

def call_function(ds):
   ds['new_age'] = np.nan
   ds.loc[ds['col'] == 0, 'new_age'] = ds['age'].mul(0.012345678901).round(12)

   return ds

df = call_function(df)

If you are unable to modify the function, run method on splits of data frame and concat or append together. Any new columns in other split will be have values filled with NAs.

def call_function(ds):
   ds['new_age'] = (ds['age']* 0.012345678901).round(12)
   return ds

df = pd.concat([call_function(df[df['col'] == 0].copy()),
                df[df['col'] != 0].copy()])
Sign up to request clarification or add additional context in comments.

2 Comments

I got the error with second way: TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"
Whoops! pd.concat takes a list and not comma-separated objects. See edit.

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.