gpt4 book ai didi

python - 仅当 "."是 python 数据框列中的唯一值时才替换

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:22 26 4
gpt4 key购买 nike

我有一个正在使用的数据框,其中缺失值用点 (.) 指定,我正在尝试用“Not_Given”替换缺失的数据。但是,其他一些列有“。”在作为较长字符串一部分的字符串中。我已经设置了一个迷你数据框来测试下面的替换方法:

test_df = pd.DataFrame({"a": ["1", "2", "3", "4", "5"], "b": ["1.0", "2.0", "3.0", "4.0", "5.0"], "c": ["a", "b", "c", ".", "a.b"]})
test_df

打印出以下数据框:

enter image description here

我编写了以下代码来尝试替换单个“.”值(第 3 列的索引 3):

for col in ["a", "b", "c"]:
test_df[col] = test_df[col].str.replace(".", "Not_Given")

test_df

这将返回输出:

enter image description here

显然这是在替换每个“.”它在数据框中出现,因此值 1.0 被 1Not_Given0 替换。

我也试过下面的代码:

for col in ["a", "b", "c"]:
test_df[col] = test_df[col].str.replace("\.{1,1}", "Not_Given")

仍然具有与上面相同的输出。

有没有办法只在只有“.”的情况下才替换?没有其他字符的值?

最佳答案

试试 Pandas replace功能:

test_df.replace({'.': 'Not_Given'})

结果:

   a    b          c
0 1 1.0 a
1 2 2.0 b
2 3 3.0 c
3 4 4.0 Not_Given
4 5 5.0 a.b

关于python - 仅当 "."是 python 数据框列中的唯一值时才替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332062/

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