如何基于指定列表为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_make | vehicle_model | vehicle_year | vehicle_make_category |
|---|---|---|---|
| Toyota | Corolla | 2016 | Non-Luxury |
| Hyundai | Sonata | 2016 | Non-Luxury |
| Cadillac | DTS | 2006 | Uncategorized |
| Toyota | Prius | 2014 | Non-Luxury |
| Kia | Optima | 2015 | Non-Luxury |
Why this works:
df['vehicle_make'].isin(luxury)creates a boolean mask where each row isTrueif the make is in the luxury list.- The outer
np.where()uses that mask to assign 'Luxury' where true, otherwise moves to the innernp.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
相关产品推荐
相关产品推荐

