Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

前端 未结 2 1803
醉梦人生
醉梦人生 2020-11-28 18:42

I am working with the pandas library and I want to add two new columns to a dataframe df with n columns (n > 0).
These new columns result from the applicati

2条回答
  •  执笔经年
    2020-11-28 19:00

    I'd just use zip:

    In [1]: from pandas import *
    
    In [2]: def calculate(x):
       ...:     return x*2, x*3
       ...: 
    
    In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
    
    In [4]: df
    Out[4]: 
       a  b
    0  1  2
    1  2  3
    2  3  4
    
    In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
    
    In [6]: df
    Out[6]: 
       a  b  A1  A2
    0  1  2   2   3
    1  2  3   4   6
    2  3  4   6   9
    

提交回复
热议问题