Adding new column to existing DataFrame in Python pandas

后端 未结 25 1235
你的背包
你的背包 2020-11-22 01:15

I have the following indexed DataFrame with named columns and rows not- continuous numbers:

          a         b         c         d
2  0.671399  0.101208 -         


        
25条回答
  •  感情败类
    2020-11-22 01:24

    If the data frame and Series object have the same index, pandas.concat also works here:

    import pandas as pd
    df
    #          a            b           c           d
    #0  0.671399     0.101208   -0.181532    0.241273
    #1  0.446172    -0.243316    0.051767    1.577318
    #2  0.614758     0.075793   -0.451460   -0.012493
    
    e = pd.Series([-0.335485, -1.166658, -0.385571])    
    e
    #0   -0.335485
    #1   -1.166658
    #2   -0.385571
    #dtype: float64
    
    # here we need to give the series object a name which converts to the new  column name 
    # in the result
    df = pd.concat([df, e.rename("e")], axis=1)
    df
    
    #          a            b           c           d           e
    #0  0.671399     0.101208   -0.181532    0.241273   -0.335485
    #1  0.446172    -0.243316    0.051767    1.577318   -1.166658
    #2  0.614758     0.075793   -0.451460   -0.012493   -0.385571
    

    In case they don't have the same index:

    e.index = df.index
    df = pd.concat([df, e.rename("e")], axis=1)
    

提交回复
热议问题