【问题标题】:Replace Column2 value with Dictionary Key Where Column1 Condition is met用满足 Column1 条件的字典键替换 Column2 值
【发布时间】:2019-12-09 12:12:16
【问题描述】:

我有一本将数字标签与分类标签相关联的字典。

dict = {
0:'cat',
1:'dog', 
2:'fish
}

我的数据框(df)输出如下:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        1               Thing       1
Person     Steve           Pet         1
Place      Texas           Place       Virginia

我想将“1”替换为“狗”。

我试过了。

df.replace({df.loc[df['Feature'] == 'Pet']: dict})

但是,我知道这只是在匹配 Feature 列,而不是从 Feature 值中提取值以在字典中匹配。

我的数据框(df)输出应该是:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        dog             Thing       1
Person     Steve           Pet         dog
Place      Texas           Place       Virginia

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    考虑到你的情况,你可以这样做:

    df['Feature Value'].map(dict).fillna(df['Feature Value'])
    

    这是非详尽映射,map() 函数根据您在字典中定义的标签进行映射,而 fillna() 有助于保留不匹配的现有值。此外,map()repalce() 快​​得多

    【讨论】:

      【解决方案2】:

      您可以根据特征替换单个特征/特征值集的值。

      注意:由于 Feature_Value 列是对象类型,所以我将所选值用作 type(int)。

      df.loc[df['Feature'] == 'Pet', 'Feature_Value']= df.loc[df['Feature'] == 'Pet', 'Feature_Value'].astype(int).replace(d)
      
      df.loc[df['Feature1'] == 'Pet', 'Feature1_Value']= df.loc[df['Feature1'] == 'Pet', 'Feature1_Value'].astype(int).replace(d)
      
      
          Feature Feature_Value   Feature1    Feature1_Value
      0   Pet     dog             Thing       1
      1   Person  Steve           Pet         dog
      2   Place   Texas           Place       Virginia
      

      【讨论】:

        猜你喜欢
        • 2014-12-19
        • 2018-09-30
        • 2018-05-27
        • 2017-12-08
        • 2019-02-03
        • 1970-01-01
        • 2020-04-02
        • 2018-08-24
        • 1970-01-01
        相关资源
        最近更新 更多