python - 根据字典替换列中的值 (Pandas)

标签 python pandas dictionary dataframe replace

我有一个包含主题 # 映射的文本文件 (subject_ID_dict.csv),如下所示:

30704   703
30705   849
30714   682
30720   699
30727   105
30729   708
30739   707
30757   854
30758   710
30763   724
30771   715
30773   99
30777   719
30779   717
30798   728
30805   732
30809   727
30831   734
30838   736
30868   735
30908   742
30929   115
30942   747
30944   743
30993   745
31006   116
31018   113
31040   758
31055   756
31057   755
31058   754
31068   760
31091   885
31147   764
31193   765
31196   767
31202   766
31209   117
31235   118
31268   772
31275   771
40017   -88
40018   542
40021   557
40023   28

我想将其作为字典加载并使用它来替换 data.csv 中第一列中的值。例如,40023 将变为 28。

这是我的代码:

import pandas as pd
from collections import defaultdict

# load text file where we want to replace things
df = pd.read_csv('data.csv', header=0)

# make dictionary
d = defaultdict(list)
with open('subject_ID_dict.csv') as f:
    for line in f:
        line=str(line)
        k, v = map(int, line.split())
        d[k].append(v)
print df['subid'].replace(d, inplace=True)

当我打印 d 时,我得到这个(片段因为它很长):

defaultdict(<type 'list'>, {30720: [699], 30727: [105], 30729: [708], 30739: [707], 70319: [7066], 30757: [854], 30758: [710], 30763: [724], 30771: [715], 30773: [99], 70514: [7052], 30777: [719], 30779: [717], 70721: [-88], 70405: [-88], 30798: [728], 50331: [503310], 30805: [732], 30809: [727], 70674: [7080], 30831: [734], 30838: [736], 

如何使用 subject_ID_dict.csv 中的字典 d 重新映射 data.csv 的“subjid”列?

最佳答案

首先,为了方便快速替换,创建一个平面字典。不要使用 defaultdict

d = {}
with open('subject_ID_dict.csv') as f:
    for line in f:
        k, v = map(int, line.split())
        d[k] = v

接下来,使用df.map转换您的 subid 列。

df['subid'] = df['subid'].map(d)

关于python - 根据字典替换列中的值 (Pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45471427/

相关文章:

python - Docker 镜像错误 : "/bin/sh: 1: [python,: not found"

python - 运行许多Python线程并获取每个线程的返回值

python - 处理生成器中抛出的异常

Python scapy 显示 ping (echo) 请求的 ip

python - 将 Dask 标量转换为整数值(或将其保存到文本文件)

python - 如何使用多索引 df 中的 2 行执行计算并将结果附加为新行?

python - 按列值扩展数据框

c# - MongoDB 序列化 Dictionary<MyEnum,object>

python错误 'dict'对象没有属性: 'add'

python - 在 Python 中使用 csv 文件使用字典计算字符串中的单词数