Get two return values from Pandas apply

You can apply pd.Series

df.drop('Double', 1).join(df.Double.apply(pd.Series, index=['D1', 'D2']))

   A  B  C  D1  D2
0  1  2  3   1   2
1  2  3  2   3   4
2  3  4  4   5   6
3  4  1  1   7   8

Equivalently

df.drop('Double', 1).join(
    pd.DataFrame(np.array(df.Double.values.tolist()), columns=['D1', 'D2'])
)

setup
using @GordonBean's df

df = pd.DataFrame({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[3,2,4,1], 'Double': [(1,2), (3,4), (5,6), (7,8)]})

You can get the index in a separate column like this:

df[['phour','index']] = df.apply(lambda row: pd.Series(list(fun(row))), axis=1)

Or if you modify fun slightly:

def fun(row):
    s = [sum(row[i:i+2]) for i in range (len(row) -1)]
    ps = s.index(max(s))
    return [max(s),ps]

Then the code becomes a little less convoluted:

 df[['phour','index']] = df.apply(lambda row: pd.Series(fun(row)), axis=1)

If you are just trying to get the max and argmax, I recommend using the pandas API:

DataFrame.idxmax

So:

df = pd.DataFrame({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[3,2,4,1]})
df

    A   B   C
0   1   2   3
1   2   3   2
2   3   4   4
3   4   1   1

df['Max'] = df.max(axis=1)
df['ArgMax'] = df.idxmax(axis=1)
df    

    A   B   C   Max ArgMax
0   1   2   3   3   C
1   2   3   2   3   B
2   3   4   4   4   B
3   4   1   1   4   A

Update:
And if you need the actual index value, you can use numpy.ndarray.argmax:

df['ArgMaxNum'] = df[['A','B','C']].values.argmax(axis=1)


    A   B   C   Max ArgMax  ArgMaxNum
0   1   2   3   3   C   2
1   2   3   2   3   B   1
2   3   4   4   4   B   1
3   4   1   1   4   A   0

Tags:

Python

Pandas