How to use the capitalize() function in pandas
Overview
The capitalize() method in pandas capitalizes the first character of a string and lowercases the rest. It can also be applied to a column in the pandas DataFrame.
Syntax
str.capitalize()
Example
The following code will demonstrate how to use the capitalize() function.
import pandas as pd# Create a DataFramedf = pd.DataFrame({"name": ["marIa","pAUl","EVa","Oliver","seBasTian","CamilA"],"age":[20,22,32,26,29,30],"salary":[2000,2500,4000,3500,4200,3000],"gender":["female","male","female","male","male","female"]})# Convert first character to uppercase and lowercase the rest using capitalize()print(df["name"].str.capitalize())
Explanation
- Line 1: We import the pandas library.
- Lines 4–10: We create a DataFrame,
df, from a dictionary. - Line 13: We use the
capitalize()function to uppercase the first letter of thenamecolumn and lowercase the rest.