You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中如何将字符串列首字母大写及批量统一设备名称?

Fixing Case Standardization for Pandas String Column

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:16:01