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

前端 未结 3 1681
迷失自我
迷失自我 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-16 23:47

    Maybe it is what you are looking for.

    df=pd.DataFrame(columns=['A','B'],data=np.arange(6).reshape(3,2))
    
    df['C'], df['D'] = df['A'], df['A']
    df['E'], df['F'] = 0, 1
    
    # Result
       A  B  C  D  E  F
    0  0  1  0  0  0  1
    1  2  3  2  2  0  1
    2  4  5  4  4  0  1
    
    0 讨论(0)
  • 2021-01-17 00:06
    for c in ['C', 'D']:
        df[c] = d['A']
    
    df['C'] = 0
    df['D'] = 1
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题