Python Pandas: Capitalize First Letter, Lowercase Rest in Column
Here's a Python script using the pandas library to capitalize the first letter and lowercase the rest of the text in the 'product' column of a dataframe:
import pandas as pd
# Create a sample dataframe
df = pd.DataFrame({'product': ['APPLE', 'banana', 'Cherry', 'grape']})
# Apply titlecase to the 'product' column
df['product'] = df['product'].apply(lambda x: x.title())
print(df)
Output:
product
0 Apple
1 Banana
2 Cherry
3 Grape
In this script:
- We import the
pandaslibrary. - We create a sample dataframe with a 'product' column containing fruit names.
- The
apply()method applies a lambda function to each element in the 'product' column. - The lambda function uses the
title()method to capitalize the first letter of each word and convert the rest to lowercase. - Finally, we print the updated dataframe with the modified 'product' column.
原文地址: https://www.cveoy.top/t/topic/nTJO 著作权归作者所有。请勿转载和采集!