【问题标题】:Iterate over df and replace values with a dict遍历 df 并用 dict 替换值
【发布时间】:2021-12-13 17:14:18
【问题描述】:

我的情况与此示例类似。 我有一个 5 行 5 列的 pandas 数据框。

我在这个df中只有0和1:

而且我有一个字典告诉我,例如,如果第一列中的值为 0,则为“G”,如果值为 1,则为“A”,如下所示:

 dict = {0: {'0': 'G', '1': 'A'},
     1: {'0': 'G', '1': 'A'},
     2: {'0': 'T', '1': 'A'},
     3: {'0': 'G', '1': 'A'},
     4: {'0': 'A', '1': 'C'},
     5: {'0': 'C', '1': 'A'}}

这是我的问题.. 我如何遍历行和列以用我的 df 上的 dict 值替换为 0、1?

前两行的预期结果:

| A | A | A | A | A | A |
|:--|:--|:--|:--|:--|--:|
| G | G | T | G | A | C |

【问题讨论】:

  • 您的预期结果不符合要求。不应该是AAAAGAGGGGGG吗?此外,您应该将您的问题编辑为minimal reproducible example,其中包含一个可以复制/粘贴的数据框;而且你不应该将你的字典命名为dict,因为这会影响内置函数。
  • 您的 DataFrame 值是字符串“0”和“1”还是数字 0 和 1?
  • @Alex - 字典按列映射值。预期的输出是有意义的。
  • 请以文本形式提供数据框(数据框构造函数或字典)

标签: python pandas dataframe dictionary replace


【解决方案1】:
data = [[random.randint(0,1) for i in range(5)] for j in range(5)]
df = pd.DataFrame(data).astype(str)

mapper =  {0: {'0': 'G', '1': 'A'},
     1: {'0': 'G', '1': 'A'},
     2: {'0': 'T', '1': 'A'},
     3: {'0': 'G', '1': 'A'},
     4: {'0': 'A', '1': 'C'},
     5: {'0': 'C', '1': 'A'}}

def maps(row):
    transform = mapper[row.name]
    for i in range(len(row)):
        row[i] = transform[row[i]]
    return row

df.apply(maps, axis=1)

【讨论】:

    【解决方案2】:

    你也可以这样做:

    for i in range(6):
        df.iloc[:, i] = df.iloc[:, i].apply(lambda x: my_dict[i][str(x)])
    

    因此您可以只定位您想要的列。

    【讨论】:

      【解决方案3】:

      您可以使用replace

      >>> df.astype(str).replace(my_dict)
      
         0  1  2  3  4  5
      0  A  A  A  A  A  A
      1  G  G  T  G  A  C
      2  G  G  T  G  A  C
      3  G  G  T  G  A  A
      4  A  A  A  A  A  C
      

      顺便说一句,不要调用你的字典dict。我在示例中使用了my_dict

      【讨论】:

        猜你喜欢
        • 2018-12-14
        • 2019-02-03
        • 2015-08-01
        • 2019-09-05
        • 2010-10-30
        • 2013-06-15
        • 2016-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多