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

如何在Pandas DataFrame中构建首5位匹配元素的重复关联映射

Solution for Grouping by First 5 Characters and Mapping to Non-Duplicate Entry

Got it, let's get this sorted for you! First, let's fix a small typo in your existing code (you referenced colA_5 lowercase when you defined it as ColA_5 uppercase) and then add the logic to build your target ColB correctly.

Step 1: Setup and Fix Initial Code

First, let's start with your data and correct the initial column handling:

import pandas as pd

# Your original dataset
data = {'ColA': ['1234567890', '1234509870', '1234589670', '1234576890', '3456789000', '3456787970']}
df = pd.DataFrame(data)

# Extract first 5 characters (ensure consistent casing for the column name)
df['ColA_5'] = df['ColA'].str[:5]

Step 2: Populate ColB with Target Values

We'll use groupby + transform to assign the first entry of each group to all rows in that group, then replace the first entry's value with non-duplicate:

# Assign the first ColA value of each group to every row in the group
df['ColB'] = df.groupby('ColA_5')['ColA'].transform('first')

# Replace the first entry of each group with "non-duplicate"
df.loc[~df.duplicated(subset='ColA_5', keep='first'), 'ColB'] = 'non-duplicate'

# Optional: Drop the intermediate ColA_5 column if you don't need it
# df = df.drop('ColA_5', axis=1)

Resulting DataFrame

Running this code will give you exactly the target output you want:

ColA          ColB
0  1234567890  non-duplicate
1  1234509870     1234567890
2  1234589670     1234567890
3  1234576890     1234567890
4  3456789000  non-duplicate
5  3456787970     3456789000

Quick Explanation

  • groupby('ColA_5')['ColA'].transform('first'): This method returns the first ColA value for each group, and broadcasts it to every row in that group—so all duplicates automatically point to the group's "base" entry.
  • ~df.duplicated(subset='ColA_5', keep='first'): This creates a boolean mask for the first entry of each group (since duplicated() returns True for all non-first entries, the ~ inverts it). We use this mask to set those rows' ColB to non-duplicate.

内容的提问来源于stack exchange,提问作者vaibhav kamthe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:14:51