【问题标题】:How do I replace all the instances of a certain character in a dataframe?如何替换数据框中某个字符的所有实例?
【发布时间】:2017-05-25 17:22:34
【问题描述】:

我有一个包含许多“?”实例的数据框在不同的行中。列的数据类型是“对象”。 现在我想替换所有的“?”与 0。 我该怎么做?

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

考虑数据框df

df = pd.DataFrame([['?', 1], [2, '?']])

print(df)

   0  1
0  ?  1
1  2  ?

replace

df.replace('?', 0)

   0  1
0  0  1
1  2  0

maskwhere

df.mask(df == '?', 0)
# df.where(df != '?', 0)

   0  1
0  0  1
1  2  0

但是,假设您的数据框在较长的字符串中包含 ?

df = pd.DataFrame([['a?', 1], [2, '?b']])

print(df)

    0   1
0  a?   1
1   2  ?b

replaceregex=True

df.replace('\?', '0', regex=True)

    0   1
0  a0   1
1   2  0b

【讨论】:

    【解决方案2】:

    我认为最好将 replace 改为 string 0,因为否则会得到混合类型 - 数字与字符串和一些 pandas 函数可能会失败:

    df.replace('?', '0')
    

    如果需要将多个? 替换为一个0 添加+ 以匹配一个或多个值:

    df = pd.DataFrame([['a???', '?'], ['s?', '???b']])
    print(df)
          0     1
    0  a???     ?
    1    s?  ???b
    
    df = df.replace('\?+', '0', regex=True)
    print (df)
        0   1
    0  a0   0
    1  s0  0b
    

    df = df.replace('[?]+', '0', regex=True)
    print (df)
        0   1
    0  a0   0
    1  s0  0b
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2011-04-05
      • 2022-12-10
      相关资源
      最近更新 更多