相关疑难解决方法(0)

pandas应用函数将多个值返回到pandas dataframe中的行

我有一个带有timeindex的数据帧和包含3D向量坐标的3列:

                         x             y             z
ts
2014-05-15 10:38         0.120117      0.987305      0.116211
2014-05-15 10:39         0.117188      0.984375      0.122070
2014-05-15 10:40         0.119141      0.987305      0.119141
2014-05-15 10:41         0.116211      0.984375      0.120117
2014-05-15 10:42         0.119141      0.983398      0.118164
Run Code Online (Sandbox Code Playgroud)

我想对每个也返回向量的行应用转换

def myfunc(a, b, c):
    do something
    return e, f, g
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

df.apply(myfunc, axis=1)
Run Code Online (Sandbox Code Playgroud)

我最终得到了一个Pandas系列,其元素是元组.这是因为申请将取得myfunc的结果而不解压缩它.如何更改myfunc以便我获得一个包含3列的新df?

编辑:

所有解决方案都起作用 Series系列解决方案允许列名,List解决方案似乎执行得更快.

def myfunc1(args):
    e=args[0] + 2*args[1]
    f=args[1]*args[2] +1
    g=args[2] + args[0] * args[1]
    return pd.Series([e,f,g], index=['a', 'b', 'c'])

def myfunc2(args):
    e=args[0] + 2*args[1]
    f=args[1]*args[2] +1
    g=args[2] + args[0] * args[1]
    return [e,f,g]

%timeit …
Run Code Online (Sandbox Code Playgroud)

python pandas

42
推荐指数
7
解决办法
5万
查看次数

标签 统计

pandas ×1

python ×1