I have a dataframe with multiple blank values and different data types per column. For example I have the following dataframe I want to select the columns "Name", "Country" and "Job" and apply capwords to all this column only if value is ALL CAPSLOCK (can convert all into str before and that is not a problem). So this dataframe:
ID Name Country Job
1 PAULO BRAZil JOHN'S DRIVER
2 Joao $ -
3 Maria np.nan DriveR
3 MARIA Portugal DRIVER
4 PEdro ARGENTINA DRIVER
Would return this output:
ID Name Country Job
1 Paulo BRAZil John's Driver
2 Joao $ -
3 Maria np.nan DriveR
3 Maria Portugal Driver
4 PEdro Argentina Driver
What would be the best way to do it?
CodePudding user response:
Let's try applymap
for each value
import string
cols = ['Name', 'Country', 'Job']
df[cols] = df[cols].applymap(lambda val: string.capwords(val) if val.isupper() else val)
print(df)
ID Name Country Job
0 1 Paulo BRAZil John's Driver
1 2 Joao $ -
2 3 Maria np.nan DriveR
3 3 Maria Portugal Driver
4 4 PEdro Argentina Driver
5 5 PEdro Argentina Driver