Creating multiple new columns from one column using Pandas

Apply pandas function to column to create multiple new columns ?

Asked on December 14, 2018 in Pandas.
Add Comment


  • 2 Answer(s)

    One can solve this using the function df.merge:

    df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})),
    left_index=True, right_index=True)
       textcol   feature1   feature2
    0  0.772692  1.772692  -0.227308
    1  0.857210  1.857210  -0.142790
    2  0.065639  1.065639  -0.934361
    3  0.819160  1.819160  -0.180840
    4  0.088212  1.088212  -0.911788
    
    Answered on December 14, 2018.
    Add Comment

    Try the following which was useful :

    df = pd.DataFrame({'textcol' : np.random.rand(5)})
    df
    textcol
    0  0.626524
    1  0.119967
    2  0.803650
    3  0.100880
    4  0.017859
    df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))
      feature1   feature2
    0  1.626524  -0.373476
    1  1.119967  -0.880033
    2  1.803650  -0.196350
    3  1.100880  -0.899120
    4  1.017859  -0.982141
    

    After doing this you get.,

    pd.concat([df, df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))], axis=1)
        textcol   feature1   feature2
    0  0.626524  1.626524  -0.373476
    1  0.119967  1.119967  -0.880033
    2  0.803650  1.803650  -0.196350
    3  0.100880  1.100880  -0.899120
    4  0.017859  1.017859  -0.982141
    
    Answered on December 14, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.