Create multiple columns from multiple return value of lambda function in python DataFrame

后端 未结 3 1474
萌比男神i
萌比男神i 2021-01-22 17:54

Att, I want to create multiple columns from lambda function\'s multiple return values in python DataFrame.

Similar with the last line of my demo code.

Is there

相关标签:
3条回答
  • 2021-01-22 18:14

    The solution is to understand the error message "too many values to unpack." When Python encounters an unpacking expression like:

    a,b = x
    

    it iterates over x and assigns the first value to a, the second to b, etc. If x is of exactly length 2 this statement will execute without error, but if x has three elements it will raise "too many values to unpack."

    Your last line of code will only work if the iterator produced by the zip() function has EXACTLY two elements. That, apparently, is not the case. It's important to realize that the problem has nothing to do with lambda or dataframes, but with the basics of Python unpacking.

    0 讨论(0)
  • 2021-01-22 18:21

    One way would be to wrap the return value in pd.Series in order to assign to new dataframe columns.

    g = lambda x: pd.Series(f_polyfit(x.y1, x.y2, x.y3, x.y5, x.y5, degree=1))
    df[['slope', 'R2']] = df.apply(g, axis=1)
    
    0 讨论(0)
  • 2021-01-22 18:25

    An alternative to using pd.Series is to turn the output into a list. You can then assign the new columns as:

    df[['slope', 'R2']] = pd.DataFrame(df.apply(lambda x: f_polyfit(x)).tolist(), 
    index=df.index)
    
    0 讨论(0)
提交回复
热议问题