[leetcode - 30 Days of Pandas] Day7

정대현·2023년 8월 26일

Day7. String Methods - Fix Names in a Table

Problem

Table: Users

Column NameType
user_idint
namevarchar

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_idname
1aLice
2bOB

Output:

user_idname
1Alice
2Bob

Solution

# 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

Lean new method

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]

pandas.Series.str.capitalize

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]



reference

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]

python document - string methods [3]

0개의 댓글