我有一个需要返回多个值的函数
:
def max_dd(ser):
...
compute i,j,dd
return i,j,dd
如果我有这样的代码调用这个函数传入 series
:
date1, date2, dd = df.rolling(window).apply(max_dd)
但是,我得到一个错误:
pandas.core.base.DataError: No numeric types to aggregate
如果我从 max_dd
返回单个值,一切都很好。如何从“apply
”函数返回多个值?
最佳答案
滚动应用只能产生单个数值。滚动应用不支持多次返回,甚至不支持非数字返回(就像字符串一样简单)。这个问题的任何答案都可以解决。
也就是说,一个可行的解决方法是利用 rolling
对象是可迭代的这一事实(从 pandas 1.1.0
开始)。
What’s new in 1.1.0 (July 28, 2020)
- 使 pandas.core.window.rolling.Rolling 和 pandas.core.window.expanding.Expanding 可迭代( GH11704 )
意味着可以利用滚动函数更快的分组和索引操作,但使用 python 获得更灵活的行为:
def some_fn(df_):
"""
When iterating over a rolling window it disregards the min_periods
argument of rolling and will produce DataFrames for all windows
The input is also of type DataFrame not Series
You are completely responsible for doing all operations here,
including ignoring values if the input is not of the correct shape
or format
:param df_: A DataFrame produced by rolling
:return: a column joined, and the max value within the window
"""
return ','.join(df_['a']), df_['a'].max()
window = 5
results = pd.DataFrame([some_fn(df_) for df_ in df.rolling(window)])
示例 DataFrame 和输出:
df = pd.DataFrame({'a': list('abdesfkm')})
df
:
a
0 a
1 b
2 d
3 e
4 s
5 f
6 k
7 m
结果
:
0 1
0 a a
1 a,b b
2 a,b,d d
3 a,b,d,e e
4 a,b,d,e,s s
5 b,d,e,s,f s
6 d,e,s,f,k s
7 e,s,f,k,m s
关于python - 从 Pandas 滚动应用函数返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69006887/