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

如何将DataFrame中宝马车型号列按首字符替换为对应系列?

宝马车型系列转换实现方案

方法一:精准首字符判断(推荐)

用str.startswith替代str.contains,避免匹配到车型中间含1/2的情况,结合numpy.where批量处理整列:

import pandas as pd
import numpy as np

# 假设你的DataFrame名为df
df['Series'] = np.where(df['Model'].str.startswith('1'), 'serie1',
                        np.where(df['Model'].str.startswith('2'), 'serie2', 
                                 None))  # 其他车型可设为空或自定义默认值

方法二:自定义函数批量映射

如果需要扩展更多规则,用apply调用自定义函数更灵活:

def map_series(model):
    first_char = str(model)[0]
    if first_char == '1':
        return 'serie1'
    elif first_char == '2':
        return 'serie2'
    return None

df['Series'] = df['Model'].apply(map_series)

方法三:提取首字符后字典映射

先提取车型首字符,再用字典直接映射对应系列:

# 一步完成映射,无需中间列
df['Series'] = df['Model'].str[0].map({'1': 'serie1', '2': 'serie2'})

注意事项

  • 若Model列存在非字符串类型数据,先转字符串:df['Model'] = df['Model'].astype(str)
  • str.contains('1')会匹配所有含1的车型(如318、M135),不符合你"首字符判断"的需求,因此不建议使用。

内容的提问来源于stack exchange,提问作者eduardo capel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:20:26