How to apply custom function to pandas data frame for each row

后端 未结 4 1829
刺人心
刺人心 2021-02-02 11:09

I want to apply a custom function and create a derived column called population2050 that is based on two columns already present in my data frame.

import pandas          


        
4条回答
  •  轮回少年
    2021-02-02 11:28

    You can achieve the same result without the need for DataFrame.apply(). Pandas series (or dataframe columns) can be used as direct arguments for NumPy functions and even built-in Python operators, which are applied element-wise. In your case, it is as simple as the following:

    import numpy as np
    
    facts['pop2050'] = facts['population'] * np.exp(35 * facts['population_growth'])
    

    This multiplies each element in the column population_growth, applies numpy's exp() function to that new column (35 * population_growth) and then adds the result with population.

提交回复
热议问题