Dataframe Apply method to return multiple elements (series)

前端 未结 4 395
粉色の甜心
粉色の甜心 2021-01-19 21:15
import pandas as pd

Let\'s say I have a dataframe like so:

df = pd.DataFrame({\"a\":range(4),\"b\":range(1,5)})
         


        
4条回答
  •  粉色の甜心
    2021-01-19 21:52

    the following solution to this frustratingly frustrating question works for me. I found the original suggestion in another StackOverflow post a while ago. The trick is to wrap up the return values into a Series like this:

    def divideAndMultiply(x,y):
        return pd.Series([x/y, x*y])
    

    Then this works as you wanted:

    df[['e','f']] = df.apply( lambda x: divideAndMultiply(x["a"],2) , axis =1)
    

提交回复
热议问题