【问题标题】:Best python data structure to replace values in a column?替换列中值的最佳python数据结构?
【发布时间】:2020-12-23 03:00:01
【问题描述】:

我正在使用需要替换 1 列中的值的数据框。我的本能是去找一个 python 字典但是,这是我的数据看起来像的一个例子(original_col):

original_col  desired_col
cat           animal
dog           animal
bunny         animal
cat           animal
chair         furniture
couch         furniture
Bob           person
Lisa          person

字典看起来像:

my_dict: {'animal': ['cat', 'dog', 'bunny'], 'furniture': ['chair', 'couch'], 'person': ['Bob', 'Lisa']}

我不能使用典型的 my_dict.get(),因为我要检索相应的 KEY 而不是值。字典是最好的数据结构吗?有什么建议吗?

【问题讨论】:

  • 你需要 reverse 映射。

标签: python-3.x pandas dataframe dictionary data-structures


【解决方案1】:

翻翻你的字典:

my_new_dict = {v: k for k, vals in my_dict.items() for v in vals}

注意,如果您的值如下:dog->animal, dog->person

【讨论】:

    【解决方案2】:

    DataFrame.replace 已经接受特定结构的字典,因此您无需重新发明轮子:{col_name: {old_value: new_value}}

    df.replace({'original_col': {'cat': 'animal', 'dog': 'animal', 'bunny': 'animal',
                                 'chair': 'furniture', 'couch': 'furniture', 
                                 'Bob': 'person', 'Lisa': 'person'}})
    

    您也可以使用Series.replace,然后只需要内部字典:

    df['original_col'].replace({'cat': 'animal', 'dog': 'animal', 'bunny': 'animal',
                                'chair': 'furniture', 'couch': 'furniture', 
                                'Bob': 'person', 'Lisa': 'person'})
    

    【讨论】:

      【解决方案3】:

      pandas map() 函数使用字典或其他 pandas Series 来执行这种查找,IIUC:

      # original column / data
      data = ['cat', 'dog', 'bunny', 'cat', 'chair', 'couch', 'Bob', 'Lisa']
      
      # original dict
      my_dict: {'animal': ['cat', 'dog', 'bunny'], 
                'furniture': ['chair', 'couch'], 
                'person': ['Bob', 'Lisa']
               }
      
      # invert the dictionary
      new_dict = { v: k 
                   for k, vs in my_dict.items()
                   for v in vs }
      
      # create series and use `map()` to perform dictionary lookup
      df = pd.concat([
          pd.Series(data).rename('original_col'),
          pd.Series(data).map(new_values).rename('desired_col')], axis=1)
      
      print(df)
      
        original_col desired_col
      0          cat      animal
      1          dog      animal
      2        bunny      animal
      3          cat      animal
      4        chair   furniture
      5        couch   furniture
      6          Bob      person
      7         Lisa      person
      

      【讨论】:

        猜你喜欢
        • 2013-11-02
        • 1970-01-01
        • 2017-08-03
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        相关资源
        最近更新 更多