how to apply user defined function to Pandas DataFrame - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: how to apply user defined function to Pandas DataFrame (/thread-20586.html) |
how to apply user defined function to Pandas DataFrame - evelynow - Aug-20-2019 i made a user defined function with 4 arguements. these 4 arguements are the 4 columns of the panda dataframe. how do i apply it? i wish to make a new column to store all the return values from the user defined function. this is my user defined function: cash_flow_list = [] def all_cash_flows (fv, cp_rate, maturity_year, coupon_per_year): for i in range (1,maturity_year*coupon_per_year + 1): if i == (maturity_year*coupon_per_year): cash_flow_list.append((fv*cp_rate/coupon_per_year) + fv ) else: cash_flow_list.append((fv*cp_rate/coupon_per_year)) return (cash_flow_list)(only 1 value will be returned. i need the values for my 200 rows of panda data frame) i have a panda data frame which consist of 200 rows and 4 columns, the 4 columns store the values for the fv, cp_rate, maturity_year and coupon_per_year. how do i apply the user defined function and store the answers in a new column? RE: how to apply user defined function to Pandas DataFrame - Ecniv - Aug-20-2019 perhaps try something like : df['cashflow'] = df.apply( cash_flow_list(df['fv'],df['cp_rate'],df['maturity_year'],df['coupon_per_year'])** But I am new to python and pandas - usually doesnt do what I want/need RE: how to apply user defined function to Pandas DataFrame - evelynow - Aug-20-2019 hi, thank you for your suggestion. i tried but it seems to be an error. i just started python a few backs so i am really beginnger.
RE: how to apply user defined function to Pandas DataFrame - scidam - Aug-20-2019 When you are working with Pandas, it is important to think in vectorized form. Don't use loops, you can operate with entire dataframe columns. Express what you are trying to do. I don't know what "fv, cp_rate, maturity_year, coupon_per_year" variables are. Are they assumed to be columns of a dataframe? If so, you can likely rewrite your function in fully vectorized form. |