Fundamentals 3 min read

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.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Combine Province, City, and District Columns in Pandas with Vectorized Operations

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondata-processingpandasCode Tutorialvectorized operations
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.