替换多列中的“.0”

2024-06-01 02:47:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件需要清理。我想删除有时出现在我的列中的“.0”。但无论我尝试了什么,它都会给我返回错误或删除所有内容:

Pos;ArtNo;Netto;RechnNo;LiefeNo
100;3441223;820,4;1122;555.0
200;3441223;820,4;1122;555.0
300;1492133;224,88;123.0;2200
400;7000061;8,99;12000;2200
500;7003581;2,09;1111.0;100

它应该是什么样子的:

Pos;ArtNo;Netto;RechnNo;LiefeNo
100;3441223;820,4;1122;555
200;3441223;820,4;1122;555
300;1492133;224,88;123;2200
400;7000061;8,99;12000;2200
500;7003581;2,09;1111;100

我试过:

cols = ['ArtNo','RechnNo','LiefeNo']
file_in[cols] = file_in[cols].astype(str).apply(lambda x: x.str.rstrip('.0'))

去掉了所有的零,这不是我想要的

我也试过:

file_in[cols] = file_in[cols].astype(str).replace('.0','')

以及

file_in[cols] = file_in[cols].astype(str).str.replace('.0','')

这给了我错误“AttributeError:'str'对象没有属性'str

我真的不知道还能做什么:/

编辑我还尝试使用lambda替换:

file_in[cols] = file_in[cols].astype(str).apply(lambda x: x.str.replace('.0','))

也不起作用

编辑2不能使用INT,因为我的列有时会有字符串而不仅仅是数字


Tags: lambdainpos编辑错误replacefileapply
3条回答

尝试:

file_in[cols] = file_in[cols].astype(str).apply(lambda x: x.str.replace('.0',''))

忘了“不”?你知道吗

试试这个。注意\前面的.0

file_in[cols] = file_in[cols].astype(str).replace('\.0*$','', regex=True)

解释:
df.replace默认为regex=False。在regex=False上,它考虑整个词。为了让它考虑每个字符,我们必须设置regex=True。在正则表达式中,字符.被认为是任何字符的匹配模式。要强制regex将其视为文本.,我们需要使用\对其进行转义。这就是我们需要\.0的原因

尝试:

file_in[cols] = file_in[cols].astype(str).replace('\.0', '', regex=True)

相关问题 更多 >