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

Python Pandas:基于Sign列高效生成Parking Type列的方法咨询

更高效的Pandas列赋值方案

Hey there! I totally get it—nested lambda conditions can get messy and hard to read fast. Let's switch to Pandas' native vectorized operations instead, which are not only cleaner but way more efficient for large datasets. Here are two solid approaches to solve your problem:

方法1:使用np.select()(推荐多条件场景)

This method makes your rules super explicit, which is great for readability—especially if you might add more conditions later.

import pandas as pd
import numpy as np

# 定义判断条件和对应结果
conditions = [
    # 检查Sign列是否包含"MTR"(不区分大小写,处理空值)
    df['Sign'].str.contains('MTR', case=False, na=False),
    # 检查是否包含"TKT"
    df['Sign'].str.contains('TKT', case=False, na=False)
]
values = ['Meter', 'Ticket']

# 应用条件,未匹配的默认赋值"Other"
df['Parking Type'] = np.select(conditions, values, default='Other')

细节说明:

  • case=False:避免因为大小写差异(比如"mtr"或"Tkt")导致漏判
  • na=False:如果Sign列存在缺失值,会直接归为"Other"
  • 条件按顺序判断,若某行同时包含"MTR"和"TKT"(虽然你的样本里没有这种情况),会优先匹配第一个条件

方法2:嵌套np.where()(适合少条件场景)

If you only have two specific patterns to check, nested np.where() is concise and straight to the point:

df['Parking Type'] = np.where(
    df['Sign'].str.contains('MTR', case=False, na=False),
    'Meter',
    np.where(
        df['Sign'].str.contains('TKT', case=False, na=False),
        'Ticket',
        'Other'
    )
)

和你旧写法的对比

Just to highlight the improvement—your original lambda approach might look like this:

# 繁琐的lambda写法(不推荐)
df['Parking Type'] = df['Sign'].apply(lambda x: 'Meter' if 'MTR' in x else ('Ticket' if 'TKT' in x else 'Other'))

The vectorized methods above are far faster for big datasets because they avoid looping through each row individually (which is what apply(lambda...) does under the hood).

验证你的样本数据

Using your provided rows, here's what the new column would output:

  • Row 8 (Sign: 1/2P MTR SAT 7:30-1930) → Meter
  • Row 10 (Sign: 2P DIS M-SUN 0:00-23:59) → Other
  • Row 15 (Sign: 2P TKT A M-F 7:30-18:30) → Ticket
  • All other rows without MTR/TKT → Other

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:42:59