Add Multiple Columns to Pandas Dataframe from Function

后端 未结 4 1081
执笔经年
执笔经年 2021-01-30 10:41

I have a pandas data frame mydf that has two columns,and both columns are datetime datatypes: mydate and mytime. I want to add three more

4条回答
  •  失恋的感觉
    2021-01-30 11:16

    You can do this in a somewhat cleaner method by having the function you apply return a pd.Series with named elements:

    def process(row):
        return pd.Series(dict(b=row["a"] * 2, c=row["a"] + 2))
    
    
    my_df = pd.DataFrame(dict(a=range(10)))
    new_df = my_df.join(my_df.apply(process, axis="columns"))
    

    The result is:

       a   b   c
    0  0   0   2
    1  1   2   3
    2  2   4   4
    3  3   6   5
    4  4   8   6
    5  5  10   7
    6  6  12   8
    7  7  14   9
    8  8  16  10
    9  9  18  11
    

提交回复
热议问题