Comparing a dataframe on string lengths for different columns
<p>I am trying to get the string lengths for different columns. Seems quite straightforward with: </p>

<pre><code>df['a'].str.len()
</code></pre>

<p>But I need to apply it to multiple columns. And then get the minimum on it. </p>

<p>Something like: </p>

<pre><code>df[['a','b','c']].str.len().min
</code></pre>

<p>I know the above doesn't work, but hopefully you get the idea. Column <code>a</code>, <code>b</code>, <code>c</code> all contain names and I want to retrieve the shortest name. </p>

<p>Also because of huge data, I am avoiding creating other columns to save on size. </p>

<p>I think you need list comprehension, because <code>string</code> function works only with <code>Series</code> (<code>column</code>):</p>

<pre><code>print ([df[col].str.len().min() for col in ['a','b','c']])
</code></pre>

<p>Another solution with <code>apply</code>:</p>

<pre><code>print ([df[col].apply(len).min() for col in ['a','b','c']])
</code></pre>

<p>Sample:</p>

<pre><code>df = pd.DataFrame({'a':['h','gg','yyy'],
                   'b':['st','dsws','sw'],
                   'c':['fffff','','rr'],
                   'd':[1,3,5]})

print (df)

     a     b      c  d
0    h    st  fffff  1
1   gg  dsws         3
2  yyy    sw     rr  5

print ([df[col].str.len().min() for col in ['a','b','c']])
[1, 2, 0]
</code></pre>

<p><strong>Timings</strong>:</p>

<pre><code>#[3000 rows x 4 columns]
df = pd.concat([df]*1000).reset_index(drop=True)

In [17]: %timeit ([df[col].apply(len).min() for col in ['a','b','c']])
100 loops, best of 3: 2.63 ms per loop

In [18]: %timeit ([df[col].str.len().min() for col in ['a','b','c']])
The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 2.88 ms per loop
</code></pre>

<p><strong>Conclusion</strong>:</p>

<p><code>apply</code> is faster, but not works with <code>None</code>.</p>

<pre><code>df = pd.DataFrame({'a':['h','gg','yyy'],
                   'b':[None,'dsws','sw'],
                   'c':['fffff','','rr'],
                   'd':[1,3,5]})


print (df)
     a     b      c  d
0    h  None  fffff  1
1   gg  dsws         3
2  yyy    sw     rr  5

print ([df[col].apply(len).min() for col in ['a','b','c']])
</code></pre>

<blockquote>
  <p>TypeError: object of type 'NoneType' has no len()</p>
</blockquote>

<pre><code>print ([df[col].str.len().min() for col in ['a','b','c']])
[1, 2.0, 0]
</code></pre>

<p>EDIT by comment:</p>

<pre><code>#fail with None
print (df[['a','b','c']].applymap(len).min(axis=1))
0    1
1    0
2    2
dtype: int64
</code></pre>

<hr>

<pre><code>#working with None
print (df[['a','b','c']].apply(lambda x: x.str.len().min(), axis=1))
0    1
1    0
2    2
dtype: int64
</code></pre>

python pandas dataframe min string-length