How to assign values to multiple non existing columns in a pandas dataframe?

前端 未结 2 1503
囚心锁ツ
囚心锁ツ 2021-01-18 11:20

So what I want to do is to add columns to a dataframe and fill them (all rows respectively) with a single value.

import pandas as pd
import numpy as np

df          


        
相关标签:
2条回答
  • 2021-01-18 11:32

    You can using assign and pass a dict in it

    df.assign(**dict(zip(['C','D'],[arr.tolist()]*2)))
    Out[755]: 
       A  B  C  D
    0  1  2  7  7
    1  3  4  8  8
    
    0 讨论(0)
  • 2021-01-18 11:56

    For me working:

    df[["C","D"]] = pd.DataFrame([arr], index=df.index)
    

    Or join:

    df = df.join(pd.DataFrame([arr], columns=['C','D'], index=df.index))
    

    Or assign:

    df = df.assign(**pd.Series(arr, index=['C','D']))
    

    print (df)
       A  B  C  D
    0  1  2  7  8
    1  3  4  7  8
    
    0 讨论(0)
提交回复
热议问题