Pandas中如何将字符串列首字母大写及批量统一设备名称?
Hey there! Let's get your Device column standardized properly. The issue with your current code is that your mapping dictionary only contains lowercase keys ('xiaomi', 'asus'), but your DataFrame has mixed-case values like Xiaomi, Asus, and Samsung that don’t match those keys—hence the NaN entries where there’s no match.
Simplest Solution: Use str.title()
For your specific goal of making each entry's first letter uppercase and the rest lowercase, Pandas has a built-in string method that does exactly this: str.title(). It’s perfect for this scenario because it handles all mixed-case variations automatically:
import pandas as pd # Your original dataset data = { 'No': [1, 2, 3, 4, 5], 'Device': ['asus', 'Xiaomi', 'xiaomi', 'Asus', 'Samsung'] } df = pd.DataFrame(data) # Apply title case to standardize the column df['Device'] = df['Device'].str.title() print(df)
This will output exactly your desired result:
No Device 0 1 Asus 1 2 Xiaomi 2 3 Xiaomi 3 4 Asus 4 5 Samsung
Alternative: Custom Mapping with Fallback
If you ever need more control (e.g., some terms don’t follow standard title case), you can first convert all values to lowercase, apply your custom mapping, then fill any remaining NaNs with title-case versions of the original values:
f = {'xiaomi':'Xiaomi', 'asus':'Asus'} df['Device'] = df['Device'].str.lower().map(f).fillna(df['Device'].str.title())
This ensures your custom mappings are applied, and any unlisted terms still get standardized to a clean, consistent format.
内容的提问来源于stack exchange,提问作者Nabih Bawazir

