rolling apply in pandas shows "TypeError: only length-1 arrays can be converted to Python scalars"
<p>Dataframe <code>df_implied_full</code> has several columns, one of them is called <code>'USDZARV1Y Curncy'</code>, and it has only <code>floats</code>.</p>

<p>This code works:</p>

<pre><code>mad                          = lambda x: np.median(np.fabs(x - np.median(x)))
df_implied_full['madtest']   = df_implied_full['USDZARV1Y Curncy'].rolling(window=60).apply(mad)
</code></pre>

<p>This code doesn't work:</p>

<pre><code>test                         = lambda x: (x - np.median(x))
df_implied_full['rolltest2'] = df_implied_full['USDZARV1Y Curncy'].rolling(window=60).apply(test)
</code></pre>

<p>The error shown is:</p>

<blockquote>
  <p>File "pandas\algos.pyx", line 1831, in pandas.algos.roll_generic (pandas\algos.c:51581)</p>
  
  <p>TypeError: only length-1 arrays can be converted to Python scalars</p>
</blockquote>

<p>I'm using Pandas 0.18.1 and python 2.7.12</p>

<p>What is wrong with my code?</p>

<p>There is problem output of <code>x</code> in <code>lambda x: (x ...</code> is <code>numpy array</code>, so if use only <code>test = lambda x: x</code> numpy array cannot be converted to scalar values per each row. I think you need return scalar value only e.g. use <code>x[0]</code> or <code>np.median(x)</code>. The best is use custom function and test it.</p>

<p>Sample with <code>window=2</code>:</p>

<pre><code>import pandas as pd
import numpy as np

df_implied_full = pd.DataFrame({'USDZARV1Y Curncy': [1.2,4.6,7.3,4.9,1.5]})
print (df_implied_full)

def test (x):
    print (x)

    #[ 1.2  4.6]
    #[ 4.6  7.3]
    #[ 7.3  4.9]
    #[ 4.9  1.5]

    print (type(x))
    #&lt;class 'numpy.ndarray'&gt;
    #&lt;class 'numpy.ndarray'&gt;
    #&lt;class 'numpy.ndarray'&gt;
    #&lt;class 'numpy.ndarray'&gt;

    #Return only first value of list
    return x[0]

mad                          = lambda x: np.median(np.fabs(x - np.median(x)))
df_implied_full['madtest']   = df_implied_full['USDZARV1Y Curncy'].rolling(window=2).apply(test)

print (df_implied_full)
   USDZARV1Y Curncy  madtest
0               1.2      NaN
1               4.6      1.2
2               7.3      4.6
3               4.9      7.3
4               1.5      4.9
</code></pre>

<hr>

<pre><code>def test (x):
def test (x):
    print (x)

    #[ 1.2  4.6]
    #[ 4.6  7.3]
    #[ 7.3  4.9]
    #[ 4.9  1.5]

    #Return median as scalar
    return np.median(x)

mad                          = lambda x: np.median(np.fabs(x - np.median(x)))
df_implied_full['madtest']   = df_implied_full['USDZARV1Y Curncy'].rolling(window=2).apply(test)

print (df_implied_full)
   USDZARV1Y Curncy  madtest
0               1.2      NaN
1               4.6     2.90
2               7.3     5.95
3               4.9     6.10
4               1.5     3.20
</code></pre>

python arrays function pandas median