Label Excel Rows by Keywords with Pandas: A Quick Python Guide
This article demonstrates how to use Python's pandas library to read an Excel file, define a function that matches specific brand keywords in a column, assign corresponding labels such as “automobile brand” or “sports brand” to a new column, and output the results, while also providing the full code example and tips for sharing data and seeking help.
1. Introduction
The author received a question in a Python community about processing Excel data with pandas. The task is to examine column A for specific brand keywords and write a label into column C: if the cell contains any of ['吉利','奔驰','福特'] label it as "汽车品牌" (automobile brand); if it contains any of ['NIKE','李宁','安踏'] label it as "运动品牌" (sports brand).
2. Implementation
A concise solution is provided using pandas to read the Excel file, a custom function to perform the keyword matching, and the apply method to generate the new column.
import pandas as pd
df = pd.read_excel("测试数据.xlsx", names=["A", "B"])
def match_word(word):
for w in ('吉利', '奔驰', '福特'):
if w in word:
return "汽车品牌"
for w in ('NIKE', '李宁', '安踏'):
if w in word:
return "运动品牌"
else:
return None
df["res"] = df["A"].apply(lambda x: match_word(x))
print(df)The function checks each keyword list sequentially and returns the appropriate label; if no keyword matches, it returns None. Running the script produces the expected labeling in the new column.
3. Conclusion
This short guide shows how pandas can be leveraged to perform keyword‑based classification directly on Excel data, offering a practical example for data‑processing tasks in Python.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
