Table: Users
| Column Name | Type |
|---|---|
| user_id | int |
| name | varchar |
user_id is the primary key (column with unique values) for this table.
This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.
Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.
Return the result table ordered by user_id.
The result format is in the following example.
Example 1:
Input:
Users table:
| user_id | name |
|---|---|
| 1 | aLice |
| 2 | bOB |
Output:
| user_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
# my solution
import pandas as pd
def fix_names(users: pd.DataFrame) -> pd.DataFrame:
# change only the first character to uppercase and the rest to lowercase
users['name'] = users['name'].str[0].str.upper() + users['name'].str[1:].str.lower()
# sort by user_id
return users.sort_values(by=['user_id'])
# check result
data = [[1, 'aLice'], [2, 'bOB']]
Users = pd.DataFrame(data, columns=['user_id', 'name']).astype({'user_id':'Int64', 'name':'object'})
fix_names(Users)

# the other solutions [1]
# 1.
import pandas as pd
def fix_names(users: pd.DataFrame) -> pd.DataFrame:
# Apply the str.capitalize() function to fix the names
users['name'] = users['name'].str.capitalize()
# Sort the result table by user_id in ascending order
result_df = users.sort_values(by='user_id', ascending=True)
return result_df
When I check popular solutions, They use capitalize method. It works the same way as changing only the first character to uppercase and the rest to lowercase in my solution. It is simpler and more effective than my solution. Now, Let's learn about capialize method throuogh Pandas API reference. [2]
Series.str.capitalize() convert strings in the Series/Index to be capitalized. equivalent to python str.sputalize(). [3] Let's check a examle.
import pandas as pd
s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'])
s

s.str.capitalize()
There are many method similar to capitalize method. Let's check them.
s.str.title()

s.str.swapcase()
As you can see from the above results, Series.str.title() and Series.str.swapcase() are the same as python str.title() and str.swapcase().
title() convert string where words start with an uppercase character and the remaining characters are lowercase. swapcase() convert uppercase to lowercase and lowercase to uppercase. [3]
Problem
leetcode - 30 Days of Pandas / Fix Names in a Table [0]
other solutions
other solutions 1. [1]
Pandas API reference
pandas.Series.str.capitalize — pandas 2.0.3 documentation [2]