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

Pandas技术操作:DataFrame列关键词过滤及新列生成

Hey there! Let's break down these two Pandas problems step by step, using your provided sample data to make things concrete.

1. 不区分大小写地从DataFrame某列过滤关键词

To filter rows based on a keyword without worrying about uppercase/lowercase, Pandas' str.contains() method has a handy case=False parameter that does exactly this. Here's how to use it with your sample data:

import pandas as pd

# Build your sample DataFrame
sample_data = {
    "SubUnitName": [
        "Lobby Area",
        "Lobby Sensor - Bank lobby",
        "Lobby Temperature - UPS Room",
        "UPS Sensor - Electric Room",
        "Electric Sensor - electrical Room",
        "Electric Temperature - electric Room",
        "Electric Sensor"
    ]
}
df = pd.DataFrame(sample_data)

# Filter rows containing "lobby" (case-insensitive)
lobby_filtered = df[df["SubUnitName"].str.contains("lobby", case=False)]
print(lobby_filtered)

If you need to handle missing values (NaN) in the column, add na=False to the str.contains() call to avoid errors:

lobby_filtered = df[df["SubUnitName"].str.contains("lobby", case=False, na=False)]
2. 创建新列并按规则匹配取值(不区分大小写)

For this task, np.select() is a clean way to map multiple case-insensitive conditions to your desired values. We'll define our match rules in order of priority, and set unmatched rows to blank:

import numpy as np

# Define our case-insensitive conditions (order matters for overlapping matches!)
match_conditions = [
    # First: Match any variation of "Lobby"
    df["SubUnitName"].str.contains("lobby", case=False),
    # Second: Match any variation of "UPS"
    df["SubUnitName"].str.contains("ups", case=False),
    # Third: Match "Electric" or "Electrical" (either spelling, any case)
    df["SubUnitName"].str.contains("electric|electrical", case=False)
]

# Corresponding values for each condition
result_values = ["Lobby", "UPS", "Electric"]

# Create the new column; default to blank if no conditions are met
df["Category"] = np.select(match_conditions, result_values, default="")

# Check the output
print(df)

Quick note on priority:

If a row matches multiple conditions (like your sample's "Lobby Temperature - UPS Room"), it will use the value from the first matching condition in the list. If you need to adjust which keyword takes precedence, just reorder the match_conditions and result_values lists accordingly.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:17:52