Home > front end >  How to make a small letter large after a dash in pandas records?
How to make a small letter large after a dash in pandas records?

Time:04-19

I have entries in pandas, I need to change the small letter to a large letter after the dash sign. And it is best to record this change in a separate column.

Example dataframe:

data        columns_1

2020-05-20  test-word

Need result:

data        columns_1    columns_2

2020-05-20  test-word    Test-Word

I figured out that it is possible to change the first letter using:

df['columns_2'] = df['columns_1'].apply(lambda x: x.capitalize())

Is it possible to add something to this entry or is there some other method to do this?

CodePudding user response:

You need str.title:

df['columns_2'] = df['columns_1'].str.title()

output:

         data  columns_1   column-2
0  2020-05-20  test-word  Test-Word

Note that to capitalize after a dash (which is, I believe, not what you really want), you can use a regex:

df['after-dash'] = df['columns_1'].str.replace('-([a-z])',
                                               lambda m: m.group().upper(),
                                               regex=True)

output:

         data  columns_1 after-dash
0  2020-05-20  test-word  test-Word

CodePudding user response:

Building on from what you already have, creating a list and joining the words in the list will give the desired result:

df['columns_2'] = df['columns_1'].apply(lambda x: "-".join([p.capitalize() for p in x.split("-")]))
  • Related