gpt4 book ai didi

python - 将 numpy 函数应用于对整个值进行操作的 pandas.Series 对象

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:49 24 4
gpt4 key购买 nike

我想使用 numpy.unwrappandas.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)

但这看起来不太 NumPy 。有没有更好的办法?我想我总能创造一个,但这似乎也不令人满意:

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

最佳答案

你可以使用 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 数组,这不是你想要的。

关于python - 将 numpy 函数应用于对整个值进行操作的 pandas.Series 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54891900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com