'How to make a small letter large after a dash in pandas records?
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?
Solution 1:[1]
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
Solution 2:[2]
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("-")]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rawson |
