Pandas技术操作:DataFrame列关键词过滤及新列生成
Hey there! Let's break down these two Pandas problems step by step, using your provided sample data to make things concrete.
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)]
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

