I have a dataframe with a timeindex and 3 columns containing the coordinates of a 3D vector:
JavaScript
x
8
1
x y z
2
ts
3
2014-05-15 10:38 0.120117 0.987305 0.116211
4
2014-05-15 10:39 0.117188 0.984375 0.122070
5
2014-05-15 10:40 0.119141 0.987305 0.119141
6
2014-05-15 10:41 0.116211 0.984375 0.120117
7
2014-05-15 10:42 0.119141 0.983398 0.118164
8
I would like to apply a transformation to each row that also returns a vector
JavaScript
1
4
1
def myfunc(a, b, c):
2
do something
3
return e, f, g
4
but if I do:
JavaScript
1
2
1
df.apply(myfunc, axis=1)
2
I end up with a Pandas series whose elements are tuples. This is beacause apply will take the result of myfunc without unpacking it. How can I change myfunc so that I obtain a new df with 3 columns?
Edit:
All solutions below work. The Series solution does allow for column names, the List solution seem to execute faster.
JavaScript
1
20
20
1
def myfunc1(args):
2
e=args[0] + 2*args[1]
3
f=args[1]*args[2] +1
4
g=args[2] + args[0] * args[1]
5
return pd.Series([e,f,g], index=['a', 'b', 'c'])
6
7
def myfunc2(args):
8
e=args[0] + 2*args[1]
9
f=args[1]*args[2] +1
10
g=args[2] + args[0] * args[1]
11
return [e,f,g]
12
13
%timeit df.apply(myfunc1 ,axis=1)
14
15
100 loops, best of 3: 4.51 ms per loop
16
17
%timeit df.apply(myfunc2 ,axis=1)
18
19
100 loops, best of 3: 2.75 ms per loop
20
Advertisement
Answer
Just return a list instead of tuple.
JavaScript
1
29
29
1
In [81]: df
2
Out[81]:
3
x y z
4
ts
5
2014-05-15 10:38:00 0.120117 0.987305 0.116211
6
2014-05-15 10:39:00 0.117188 0.984375 0.122070
7
2014-05-15 10:40:00 0.119141 0.987305 0.119141
8
2014-05-15 10:41:00 0.116211 0.984375 0.120117
9
2014-05-15 10:42:00 0.119141 0.983398 0.118164
10
11
[5 rows x 3 columns]
12
13
In [82]: def myfunc(args):
14
e=args[0] + 2*args[1] .:
15
f=args[1]*args[2] +1 .:
16
g=args[2] + args[0] * args[1] .:
17
return [e,f,g] .:
18
.:
19
20
In [83]: df.apply(myfunc ,axis=1)
21
Out[83]:
22
x y z
23
ts
24
2014-05-15 10:38:00 2.094727 1.114736 0.234803
25
2014-05-15 10:39:00 2.085938 1.120163 0.237427
26
2014-05-15 10:40:00 2.093751 1.117629 0.236770
27
2014-05-15 10:41:00 2.084961 1.118240 0.234512
28
2014-05-15 10:42:00 2.085937 1.116202 0.235327
29