【问题标题】:How do I remove a value from a data frame row if it does not match with a dictionary mapping?如果与字典映射不匹配,如何从数据框行中删除值?
【发布时间】:2019-11-23 22:25:21
【问题描述】:

我的数据框中有一行由数字组成(其中一些是 ID,但其他只是不相关的数字),我想创建一个名称与这些 ID 匹配的新列,但删除不相关的数字。

我有一本与之匹配的字典,比如:

id_numbers = {"001" : "Matt", "002":"Chris", "003":"Jana"}

现在,我只是使用下面的代码(它很好地匹配了数字和名称),但我也复制了列中所有不相关的数字。如何仅将与字典中的名称匹配的数字复制到新列?

df['names'] = df['numbers'].replace(id_numbers )

之后,我还想从数字列中删除不在字典中的数字。非常感谢!

【问题讨论】:

    标签: python dataframe dictionary


    【解决方案1】:

    试试map:

    df['names'] = df['numbers'].map(id_numbers)
    

    或使用:

    df['names'] = df['numbers'].replace(list(id_numbers.keys()), list(id_numbers.values()))
    

    【讨论】:

    • 哇哦,When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN,完美。
    • @Adam.Er8 是的 :-)
    • @Adam.Er8 每个人每天都在学习新东西,replace 我从 jezrael 那里学到的
    猜你喜欢
    • 2019-10-26
    • 2017-08-11
    • 2018-12-24
    • 2014-11-09
    • 2011-10-02
    • 2019-11-21
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    相关资源
    最近更新 更多