Use apply() with Pandas Series
<p>I have the code below:</p>

<pre><code>import pandas as pd
frame = pd.DataFrame(np.random.randn(4,3), columns=list('bde'),index=['Utah','Ohio','Texas','Oregon'])

frame

b   d   e
Utah    0.479210    0.161892    -1.315375
Ohio    -0.572543   0.080203    -0.446178
Texas   0.052954    0.043417    0.365056
Oregon  1.462631    0.244453    2.207720

f = lambda x: x.max()-x.min() 
frame.apply(f)
</code></pre>

<p>This results to:</p>

<pre><code>b    2.035174
d    0.201035
e    3.523095
dtype: float64
</code></pre>

<p>Im trying to learn how to apply the lambda to the specific column only so I  wanted to apply the lambda to the 'd' column only. So this is what I did</p>

<pre><code>frame['d'].apply(f)
</code></pre>

<p>It results to an error though:
    AttributeError: 'float' object has no attribute 'max'</p>

<pre><code>type(frame['d'])
pandas.core.series.Series

frame['d'].dtype
dtype('float64')
</code></pre>

<p>I try to debug it. It seems that frame['d'] which is of type Series and each of the values in this series is a float and a float doesn't have a min/max attribute.</p>

<p>I thought I'm just missing something simple here, but my limited knowledge of Python and Pandas is giving me a hard time.  How do I get to apply the lambda to column 'd' only?</p>

<p>The problem is <code>.apply</code> on a Series works <em>elementwise</em>, in a <code>DataFrame</code> it works <em>by series</em> or <em>by row</em>. If you really want to use <code>.apply</code> this way, you can subset like this:</p>

<pre><code>In [9]: frame.loc[:,['d']]
Out[9]: 
               d
Utah    2.259488
Ohio    0.458926
Texas  -0.072635
Oregon  0.470217

In [10]: type(frame.loc[:,['d']])
Out[10]: pandas.core.frame.DataFrame
</code></pre>

<p>Which returns a <code>DataFrame</code>. So then you can simply do:</p>

<pre><code>In [11]: frame.loc[:,['d']].apply(lambda x: x.max()-x.min())
Out[11]: 
d    2.332124
dtype: float64
</code></pre>

<p>Note, for brevity you can simply use <code>frame[['d']]</code>, however, this makes more sense:</p>

<pre><code>In [12]: frame.d.max() - frame.d.min()
Out[12]: 2.3321235565383334
</code></pre>

<p><strong>ETA:</strong> In fact, even for the whole <code>DataFrame</code> you really don't need apply in this case, and it will certainly be slower than the following:</p>

<pre><code>In [19]: frame.max() - frame.min()
Out[19]: 
b    3.337040
d    2.332124
e    2.224037
dtype: float64
</code></pre>

python pandas lambda