Pandas DataFrame.assign arguments

前端 未结 1 1883
遥遥无期
遥遥无期 2020-12-24 13:42

QUESTION

How can assign be used to return a copy of the original DataFrame with multiple new columns added?

DESIRED RES

相关标签:
1条回答
  • 2020-12-24 14:39

    You can create multiple column by supplying each new column as a keyword argument:

    df = df.assign(C=df['A']**2, D=df.B*2)
    

    I got your example dictionary to work by unpacking the dictionary as keyword arguments using **:

    df = df.assign(**{'C': df.A.apply(lambda x: x ** 2), 'D': df.B * 2})
    

    It seems like assign should be able to take a dictionary, but it doesn't look to be currently supported based on the source code you posted.

    The resulting output:

       A   B   C   D
    0  1  11   1  22
    1  2  12   4  24
    2  3  13   9  26
    3  4  14  16  28
    
    0 讨论(0)
提交回复
热议问题