gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:47 25 4
gpt4 key购买 nike

我有一个包含许多“?”实例的数据框在不同的行。列的数据类型是“对象”。 现在我想替换所有的 '?'与 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com