Iva*_*van 5 python pandas multiple-return-values
我有一个function需要返回多个值的:
def max_dd(ser):
...
compute i,j,dd
return i,j,dd
Run Code Online (Sandbox Code Playgroud)
如果我有这样的代码调用这个函数并传入一个series:
date1, date2, dd = df.rolling(window).apply(max_dd)
Run Code Online (Sandbox Code Playgroud)
但是,我收到错误:
pandas.core.base.DataError: No numeric types to aggregate
Run Code Online (Sandbox Code Playgroud)
如果我从 中返回单个值max_dd,则一切都很好。如何从“”函数返回多个值apply?
Hen*_*ker 12
滚动应用只能生成单个数值。不支持滚动应用的多次返回,甚至不支持非数字返回(例如简单的字符串)。这个问题的任何答案都将是一个解决方法。
\n也就是说,一个可行的解决方法是利用rolling对象是可迭代的这一事实(截至pandas 1.1.0)。
1.1.0 中的新功能\xe2\x80\x99(2020 年 7 月 28 日)
\n这意味着可以利用滚动函数更快的分组和索引操作,但使用 python 获得更灵活的行为:
\ndef some_fn(df_):\n """\n When iterating over a rolling window it disregards the min_periods\n argument of rolling and will produce DataFrames for all windows\n \n The input is also of type DataFrame not Series\n \n You are completely responsible for doing all operations here,\n including ignoring values if the input is not of the correct shape\n or format\n \n :param df_: A DataFrame produced by rolling\n :return: a column joined, and the max value within the window\n """\n return \',\'.join(df_[\'a\']), df_[\'a\'].max()\n\n\nwindow = 5\nresults = pd.DataFrame([some_fn(df_) for df_ in df.rolling(window)])\nRun Code Online (Sandbox Code Playgroud)\n示例数据帧和输出:
\ndf = pd.DataFrame({\'a\': list(\'abdesfkm\')})\nRun Code Online (Sandbox Code Playgroud)\ndf:
a\n0 a\n1 b\n2 d\n3 e\n4 s\n5 f\n6 k\n7 m\nRun Code Online (Sandbox Code Playgroud)\nresult:
0 1\n0 a a\n1 a,b b\n2 a,b,d d\n3 a,b,d,e e\n4 a,b,d,e,s s\n5 b,d,e,s,f s\n6 d,e,s,f,k s\n7 e,s,f,k,m s\nRun Code Online (Sandbox Code Playgroud)\n