如何在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中每个值的出现次数,结果如下:
| col1 | col1_count |
|---|---|
| A | 3 |
| B | 2 |
| A | 3 |
| C | 1 |
| B | 2 |
| A | 3 |
方法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 Num | Address | WordInAddr | Position |
|---|---|---|---|
| 1 | Block A | Block | 1 |
| 1 | Block A | A | 2 |
| 2 | South New Jersey Street Jersey | South | 1 |
| 2 | South New Jersey Street Jersey | Jersey | 3 |
| 2 | South New Jersey Street Jersey | Street | 4 |
| 2 | South New Jersey Street Jersey | Jersey | 5 |
内容的提问来源于stack exchange,提问作者Adeeb Shaik
相关产品推荐
相关产品推荐

