Add 2 new columns to existing dataframe using apply

前端 未结 2 871
余生分开走
余生分开走 2020-12-10 02:52

I want to use the apply function that: - Takes 2 columns as inputs - Outputs two new columns based on a function.

An example is with this add_multiply function.

相关标签:
2条回答
  • 2020-12-10 03:31

    You can add result_type='expand' in the apply:

    ‘expand’ : list-like results will be turned into columns.

    df[['add', 'multiply']]=df.apply(lambda x: add_multiply(x['col1'], x['col2']),axis=1,
                                 result_type='expand')
    

    Or call a dataframe constructor:

    df[['add', 'multiply']]=pd.DataFrame(df.apply(lambda x: add_multiply(x['col1'], 
                                        x['col2']), axis=1).tolist())
    

       col1  col2  add  multiply
    0     1     3    4         3
    1     2     4    6         8
    
    0 讨论(0)
  • 2020-12-10 03:32

    anky_91's answer highlights a useful option in apply.

    For this particular case however, apply is not even required,

    df['add'], df['multiply'] = add_multiply(df['col1'],df['col2'])
    
    0 讨论(0)
提交回复
热议问题