1

I'm looking for the equivalent of R's mutate, which allows you to reference defined variables immediately after creating them within the same mutate call.

new_df <- old_df %>%
    mutate(new_col = ifelse(something, 0, 1),
           newer_col = ifelse(new_col == 0, 'yay', 'nay'))

Looking for the equivalent in python pandas.

if I create the following dataframe, I was wondering if there is a way to use .assign to do the same thing?

dic = {'names': ['jeff', 'alice', 'steph', 'john'],
       'numbers':[4, 6, 5, 7]}

df = pd.DataFrame(dic)

df = df.assign(less_than_6 = np.where(df.numbers < 6, 100, 0),
               pass_fail = np.where(df.less_than_6 == 100, 'pass', 'fail'))

The alternative I can think of is..

df['less_than_6'] = np.where(df.numbers < 6, 100, 0)
df['pass_fail'] = np.where(df.less_than_6 == 100, 'pass', 'fail')

but was wondering if there is a way to do it in the same call?

2
  • doesn't work. I get the same 'DataFrame' object has no attribute 'less_than_6' as I got before. thank you for the try though!
    – Matt W.
    Dec 18, 2017 at 1:59
  • Add it as an answer
    – BENY
    Dec 18, 2017 at 2:11

1 Answer 1

2

Using dict in assign

df.assign(**{'less_than_6' :lambda x : np.where(x['numbers'] < 6, 100, 0)}).assign(**{'pass_fail':lambda x : np.where(x['less_than_6'] == 100, 'pass', 'fail')})                                                            
Out[202]: 
   names  numbers  less_than_6 pass_fail
0   jeff        4          100      pass
1  alice        6            0      fail
2  steph        5          100      pass
3   john        7            0      fail
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.