Convert whole dataframe from lower case to upper case with Pandas
<p>I have a dataframe like the one displayed below: </p>

<pre><code># Create an example dataframe about a fictional army
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks'],
            'company': ['1st', '1st', '2nd', '2nd'],
            'deaths': ['kkk', 52, '25', 616],
            'battles': [5, '42', 2, 2],
            'size': ['l', 'll', 'l', 'm']}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'deaths', 'battles', 'size'])
</code></pre>

<p><a href="http://i.stack.imgur.com/fiOEt.png" rel="nofollow"><img src="http://i.stack.imgur.com/fiOEt.png" alt="enter image description here"></a></p>

<p>My goal is to transform every single string inside of the dataframe to upper case so that it looks like this:</p>

<p><a href="http://i.stack.imgur.com/gprF6.png" rel="nofollow"><img src="http://i.stack.imgur.com/gprF6.png" alt="enter image description here"></a></p>

<p>Notice: all data types are objects and must not be changed; the output must contain all objects. I want to avoid to convert every single column one by one... I would like to do it generally over the whole dataframe possibly.</p>

<p>What I tried so far is to do this but without success</p>

<pre><code>df.str.upper()
</code></pre>

<p>Since <code>str</code> only works for series, you can apply it to each column individually then concatenate:</p>

<pre><code>In [6]: pd.concat([df[col].astype(str).str.upper() for col in df.columns], axis=1)
Out[6]: 
     regiment company deaths battles size
0  NIGHTHAWKS     1ST    KKK       5    L
1  NIGHTHAWKS     1ST     52      42   LL
2  NIGHTHAWKS     2ND     25       2    L
3  NIGHTHAWKS     2ND    616       2    M
</code></pre>

<hr>

<p>Edit: <strong>performance comparison</strong></p>

<pre><code>In [10]: %timeit df.apply(lambda x: x.astype(str).str.upper())
100 loops, best of 3: 3.32 ms per loop

In [11]: %timeit pd.concat([df[col].astype(str).str.upper() for col in df.columns], axis=1)
100 loops, best of 3: 3.32 ms per loop
</code></pre>

<p>Both answers perform equally on a small dataframe. </p>

<pre><code>In [15]: df = pd.concat(10000 * [df])

In [16]: %timeit pd.concat([df[col].astype(str).str.upper() for col in df.columns], axis=1)
10 loops, best of 3: 104 ms per loop

In [17]: %timeit df.apply(lambda x: x.astype(str).str.upper())
10 loops, best of 3: 130 ms per loop
</code></pre>

<p>On a large dataframe my answer is slightly faster.</p>

python pandas type-conversion uppercase lowercase