python - 如何替换数据框中某个字符的所有实例?

标签 python pandas dataframe

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

最佳答案

考虑数据框 df

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

print(df)

   0  1
0  ?  1
1  2  ?

替换

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

替换regex=True

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

    0   1
0  a0   1
1   2  0b

关于python - 如何替换数据框中某个字符的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44176496/

相关文章:

python - Tkinter Reddit scraper(Tkinter 和 Praw)返回错误 "TypeError"

python - 使用正则表达式获取 pandas 数据帧列中部分匹配的行索引

python - Pandas Apply 返回矩阵而不是单列

r - R 中计算线性回归的异方差稳健置信区间的函数

Python,Pandas 匹配并查找两个数据框中的内容

python - 如何使用 python api 添加 azure devops 迭代路径选项

python - 当我们递归使用 yield 时,我们会创建 n 个迭代器吗?

python - 如何使用tensorflow进行文本分类?

pandas - 将 Pandas 数据框变成内存中的类似文件的对象?

Python - 使用 Pandas 和 openpyxl 修改现有的 excel