【问题标题】:Replacing DataFrame values with dictionary matches and a string for non-matches用字典匹配和不匹配的字符串替换 DataFrame 值
【发布时间】:2020-08-27 13:43:37
【问题描述】:

我有数据框:

df = pd.DataFrame{'col1': ['afs', 'chk', 'est', 'app'],
 'col2': ['ofcr', 'guar', 'ltv', 'gender'],
 'col3': ['code', 'mod']}

我有字典:

dict = {'ofcr':'officer','chk':'check','mod':'modification','est':'estimated','app':'application', 'gender':'gender'}

我需要遍历 df 并用它们各自的值替换数学键。我可以通过以下方式逐列执行此操作:

df["col1"] = df["col1"].map(dict)

但这会将不匹配项转换为 NaN。我想要的是保持令牌不变,但在字符串中添加“-UNKNOWN-”或类似的明显内容,以便以后处理。我试过循环:

for tok in df['col1']:
    if tok in dict.values():
        df.replace(dict, inplace=True)
    if tok not in dict.values():
        df.replace(tok, tok '-UNKNOWN', inplace=True)
    print(tok)

这也替换了匹配项(奇怪的是,在所有列中,不仅仅是传入的那个),但不影响非匹配项。

【问题讨论】:

    标签: python dictionary replace append


    【解决方案1】:

    你可以使用applymap():

    df = pd.DataFrame({'col1': ['afs', 'chk', 'est', 'app'],
     'col2': ['ofcr', 'guar', 'ltv', 'gender'],
     'col3': ['code', 'mod', 'xxx', 'zzz']})
    
    dct = {'ofcr':'officer','chk':'check','mod':'modification','est':'estimated','app':'application', 'gender':'gender'}
    
    print(df.applymap(lambda x: dct.get(x, x + '-UNKNOWN')))
    

    打印:

              col1          col2          col3
    0  afs-UNKNOWN       officer  code-UNKNOWN
    1        check  guar-UNKNOWN  modification
    2    estimated   ltv-UNKNOWN   xxx-UNKNOWN
    3  application        gender   zzz-UNKNOWN
    

    【讨论】:

    • 这很实用!它要求我用“xxx”或“zzz”等填充df创建中的所有空值。但是一旦完成,我可以删除“xxx-UNKNOWN”。
    【解决方案2】:

    在地图之后做这个额外的步骤:

    df["col1"] = df["col1"].map(dict)
    df["col1"] = df["col1"].fillna('-UNKNOWN')
    

    【讨论】:

    • 恐怕没有效果。我尝试通过一个单独的新字典 {np.NaN: "-UNKNOWN"} 传递 df,但它只是将整个 df 转换为 NaN。
    • 新的 fillna,在 .map 之后使用时确实用“-UNKNOWN”替换了每列的 NaN。但我想要的是用“-UNKNOWN”附加不匹配的内容,而不仅仅是替换它们。
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2017-03-20
    相关资源
    最近更新 更多