python - How to ask apply to return dataframe instead of series -


i'd apply function takes 4 values , returns 2 values, , use fill 2 columns in dataframe.

def gendata():     in (0,1,nan):         b in (0,1,nan):             c in (0,1,nan):                 yield a,b,c values = list(gendata()) index = np.arange(len(values))+999 df = pd.dataframe(values, columns=["a","b","c"], index=index) 

makes:

           b    c 999   0.0  0.0  0.0 1000  0.0  0.0  1.0 1001  0.0  0.0  nan ... 

picking 2 columns , applying on function returning list 2 elements gives me dataframe 2 columns:

def f2to2(x):     a,b = x     return [a+b, a*b]  result = df[["a", "b"]].apply(f2to2, axis=1) print result            b 999   0.0  0.0 1000  0.0  0.0 1001  0.0  0.0 

this can assigned dataframe so:

df[['x','y']] = result 

but picking 4 columns , applying on function returning list 2 elements gives me series of object:

def f4to2(x):     lpos, lneg, rpos, rneg = x     return [lpos+lneg, rpos+rneg]  print df[["a", "b", "c", "a"]].apply(f4to2, axis=1) 999     [0.0, 0.0] 1000    [0.0, 1.0] 1001    [0.0, nan] ... dtype: object 

and following fails

df[['x','y']] = result 

because result single series 2 required assignment.

why applying f4to2 give me series, f2to2 give me dataframe , in general how can know whether series or dataframe returned?

the documentation silent this.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -