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

如何基于指定列表为DataFrame新增vehicle_make_category列?

How to Add a Vehicle Make Category Column to Your DataFrame

Got it, let's walk through exactly how to add that vehicle_make_category column based on your luxury/non-luxury lists. Here's a step-by-step solution using vectorized operations (way faster than looping for larger datasets):

First, let's set up your DataFrame and define the category lists:

import pandas as pd
import numpy as np

# Your original data
data = {
    'vehicle_make': ['Toyota', 'Hyundai', 'Cadillac', 'Toyota', 'Kia'],
    'vehicle_model': ['Corolla', 'Sonata', 'DTS', 'Prius', 'Optima'],
    'vehicle_year': [2016, 2016, 2006, 2014, 2015]
}
df = pd.DataFrame(data)

# Your category lists
luxury = ['Bentley', 'Maserati', 'Hummer', 'Porsche', 'Lexus']
non_luxury = ['Saab', 'Mazda', 'Dodge', 'Volkswagen', 'Kia', 'Chevrolet', 'Hyundai', 'Ford', 'Nissan', 'Honda', 'Toyota']

Now, use nested np.where() to assign categories. We'll also handle cases where the make isn't in either list (like Cadillac in your example) by labeling them as "Uncategorized":

df['vehicle_make_category'] = np.where(
    # First check if make is in luxury list
    df['vehicle_make'].isin(luxury),
    'Luxury',
    # If not, check non-luxury list
    np.where(
        df['vehicle_make'].isin(non_luxury),
        'Non-Luxury',
        # If neither, mark as Uncategorized
        'Uncategorized'
    )
)

Resulting DataFrame:

vehicle_makevehicle_modelvehicle_yearvehicle_make_category
ToyotaCorolla2016Non-Luxury
HyundaiSonata2016Non-Luxury
CadillacDTS2006Uncategorized
ToyotaPrius2014Non-Luxury
KiaOptima2015Non-Luxury

Why this works:

  • df['vehicle_make'].isin(luxury) creates a boolean mask where each row is True if the make is in the luxury list.
  • The outer np.where() uses that mask to assign 'Luxury' where true, otherwise moves to the inner np.where().
  • The inner check handles non-luxury makes, and any remaining rows (like Cadillac) get 'Uncategorized'.

If you don't need the "Uncategorized" label and just want to leave those as NaN, you can simplify the inner np.where() to return np.nan instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:15:59