Combine Province, City, and District Columns in Pandas with Vectorized Operations
This article walks through a pandas data‑processing problem, showing how to concatenate province, city, and district fields using vectorized string operations with clear code examples and resulting output to help readers apply the technique.
Introduction
Hello, I'm Pipi. During the National Day holiday I asked a pandas data‑processing question in a Python community, as shown in the screenshot below.
Implementation
The solution uses vectorized operations. Two code snippets are provided.
import pandas as pd
df = pd.read_excel('test.xlsx')
# Method 1, direct construction
df['标记'] = df.省.astype('str') + '-' + df.市.astype('str') + '-' + df.区.astype('str')
# Method 2, using concat function
df['new'] = df["省"].map(str).str.cat([df["市"].map(str), df["区"].map(str)], sep='-', na_rep='?')
print(df)Running the code produces the following result:
Another user also shared an alternative implementation, illustrated below:
Conclusion
This article demonstrates how to solve a common pandas problem by concatenating province, city, and district columns using vectorized string operations, providing clear code and output to help readers apply the technique.
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.
