Big letters inside a dataframe

Viewed 50

I have a problem making capital letters inside a column. How do you write upper case str instead of lower case? and not do it manually.

import pandas as pd

cc =[1, 2, 3, 4]
aaa = ['ala', 'babcia', 'koty', 'foki']
df = pd.DataFrame({'ID': cc, 'AAA': aaa })

enter image description here

The target look of my data frame:

enter image description here

5 Answers

You can use the .upper() function in pandas along with list comprehension:

aaa = ['ala', 'babcia', 'koty', 'foki']
aaa = [x.upper() for x in aaa]

use the below line to achieve this.

df['AAA'] = df['AAA'].apply(lambda x : x.upper())

you can use pandas str upper method for this :

df['AAA'] = df['AAA'].str.upper()
df

    ID  AAA
0   1   ALA
1   2   BABCIA
2   3   KOTY
3   4   FOKI

Thought I'd do a performance test on the answers and some other solutions, so I created this dataframe:

df = pd.DataFrame(np.arange(1000000).reshape(1000000,1)).applymap(lambda x: np.random.choice(list('abcdefghijklm')))

In terms of performance, Nathan's and Nandan's were similar and the best solution if you don't define a function, because they had similar execution time:

221 ms ± 5.92 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Sammy's was slower by 20% or so, but easiest to remember:

df['AAA'] = df['AAA'].str.upper()

281 ms ± 14.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

If you wanted a 15% performance increase from the top 2 answers, you could further use one of the answers in a function... I created a million row dataframe with one lowercase letter.

def upper(df, col):
    [x.upper() for x in df[col]]
    return


%timeit upper(df, 'AAA')

177 ms ± 3.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

You can use that:

df['AAA'] = df[['AAA']].apply(lambda n: n.str.upper())
Related