set multiple Pandas DataFrame columns to values in a single column or multiple scalar values at the same time

前端 未结 3 1682
迷失自我
迷失自我 2021-01-16 23:29

I\'m trying to set multiple new columns to one column and, separately, multiple new columns to multiple scalar values. Can\'t do either. Any way to do it other than setting

3条回答
  •  一整个雨季
    2021-01-17 00:11

    The assign method will create multiple, new columns in one step. You can pass a dict() with the column and values to return a new DataFrame with the new columns appended to the end.

    Using your examples:

    df = df.assign(**{'C': df['A'], 'D': df['A']})
    

    and

    df = df.assign(**{'C': 0, 'D':1})
    

    See this answer for additional detail: https://stackoverflow.com/a/46587717/4843561

提交回复
热议问题