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

如何在Pandas中添加值出现次数列及单词位置列

问题1:如何在Pandas中添加新列展示另一列值的出现次数

有两种高效的实现方式:

方法1:value_counts() + map()

先统计目标列的频次,再通过映射将频次匹配到每一行:

import pandas as pd

# 示例数据
df = pd.DataFrame({'col1': ['A', 'B', 'A', 'C', 'B', 'A']})

# 添加频次列
df['col1_count'] = df['col1'].map(df['col1'].value_counts())

执行后col1_count列会显示col1中每个值的出现次数,结果如下:

col1col1_count
A3
B2
A3
C1
B2
A3

方法2:groupby() + transform()

通过分组后对目标列应用count变换,直接生成对应频次:

df['col1_count'] = df.groupby('col1')['col1'].transform('count')

该方法结果与方法1完全一致,适合需要保留原数据顺序的场景。


问题2:添加Position列展示WordInAddr在Address中的对应位置

针对示例中包含重复单词的场景,可通过自定义函数结合apply实现精准匹配:

步骤1:准备示例数据

df = pd.DataFrame({
    'roll Num': [1,1,2,2,2,2],
    'Address': ['Block A', 'Block A', 'South New Jersey Street Jersey', 'South New Jersey Street Jersey', 'South New Jersey Street Jersey', 'South New Jersey Street Jersey'],
    'WordInAddr': ['Block', 'A', 'South', 'Jersey', 'Street', 'Jersey']
})

步骤2:定义位置匹配函数

def get_word_position(address, target_word):
    # 拆分地址为单词列表
    words = address.split()
    # 收集目标单词所有出现的位置(从1开始计数)
    match_positions = [idx + 1 for idx, word in enumerate(words) if word == target_word]
    
    # 用计数器处理重复单词的位置匹配
    if not hasattr(get_word_position, "counter"):
        get_word_position.counter = {}
    key = (address, target_word)
    get_word_position.counter[key] = get_word_position.counter.get(key, 0) + 1
    
    return match_positions[get_word_position.counter[key] - 1]

步骤3:应用函数生成Position列

# 重置计数器,避免多次执行时的计数混乱
get_word_position.counter = {}
df['Position'] = df.apply(lambda row: get_word_position(row['Address'], row['WordInAddr']), axis=1)

执行后得到的结果与示例表格完全一致:

roll NumAddressWordInAddrPosition
1Block ABlock1
1Block AA2
2South New Jersey Street JerseySouth1
2South New Jersey Street JerseyJersey3
2South New Jersey Street JerseyStreet4
2South New Jersey Street JerseyJersey5

内容的提问来源于stack exchange,提问作者Adeeb Shaik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:23:09