将numpy函数应用于对整个值进行运算的pandas.Series对象

时间:2019-02-26 18:26:56

标签: python pandas numpy

我想在numpy.unwrap对象上使用pandas.Series函数,但似乎无法弄清楚如何应用它:

>>> import numpy as np
>>> import pandas as pd
>>>
>>> t = np.arange(0,1,0.05)
>>> ang = pd.Series((15*t)%(2*np.pi), t)
>>> np.unwrap(ang)
array([  0.  ,   0.75,   1.5 ,   2.25,   3.  ,   3.75,   4.5 ,   5.25,
         6.  ,   6.75,   7.5 ,   8.25,   9.  ,   9.75,  10.5 ,  11.25,
        12.  ,  12.75,  13.5 ,  14.25])
# this produces an np.array with the correct result, but not a Series
>>> ang.apply(np.unwrap)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\series.py", line 3192, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer
  File "c:\app\python\anaconda\2\lib\site-packages\numpy\lib\function_base.py", line 1795, in unwrap
    dd = diff(p, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\numpy\lib\function_base.py", line 1571, in diff
    slice1[axis] = slice(1, None)
IndexError: list assignment index out of range
>>> ang.map(np.unwrap)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\series.py", line 2996, in map
    arg, na_action=na_action)
  File "c:\app\python\anaconda\2\lib\site-packages\pandas\core\base.py", line 1004, in _map_values
    new_values = map_f(values, mapper)
  File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer
  File "c:\app\python\anaconda\2\lib\site-packages\numpy\lib\function_base.py", line 1795, in unwrap
    dd = diff(p, axis=axis)
  File "c:\app\python\anaconda\2\lib\site-packages\numpy\lib\function_base.py", line 1571, in diff
    slice1[axis] = slice(1, None)
IndexError: list assignment index out of range

我可以使用新系列的显式构造:

pd.Series(np.unwrap(ang), ang.index)

但是,这似乎有些麻木。有没有更好的办法?我想我总是可以创建一个,但这似乎也不令人满意:

def map_values(series, func):
    return pd.Series(func(series.values), series.index)
map_values(ang, np.unwrap)

1 个答案:

答案 0 :(得分:1)

您可以使用transform,但令人惊讶的是,它不能立即使用。我得到它来返回这样的系列:

import numpy as np
import pandas as pd

t = np.arange(0, 1, 0.05)
ang = pd.Series((15 * t) % (2 * np.pi), t)

result = ang.to_frame().transform(np.unwrap).squeeze()

直接进行result = ang.transform(np.unwrap)会返回一个numpy数组,这不是您想要的。