【发布时间】:2022-01-17 10:47:11
【问题描述】:
我的代码大致是这样的:
df[['floatcol1', 'floatcol2', 'floatcol3']] = df[['floatcol1', 'floatcol2', 'floatcol3']].astype(str)
df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']] = df[['strfloatcol1', 'strfloatcol2', 'strfloatcol3']].replace(',', '.')
但它仍在打印我的值,例如 527,1 和 847,9,而不是我想要的 527.2 和 847.9。我很困惑为什么 replace 不能替换逗号。
【问题讨论】:
-
缺少
regex=True->.replace(',', '.', regex=True) -
@HenryEcker 不,这不是问题。如要求的那样,我们想替换文字逗号。
-
我不明白 @KarlKnechtel 没有 regex=True
replace只会交换完全匹配的字符串。 即 只包含一个逗号的单元格。看来我们想在字符串中用点替换逗号。 -
OP:你期望
.astype(str)结果包含逗号吗?或者您是否正在尝试修复错误的本地化设置?或者只是什么? -
这毫无意义@KarlKnechtel 没有
regex=True它只会替换完全匹配的字符串。 仅包含一个逗号的单元格将被替换。使用regex=True,它将将单元格中包含的逗号替换为其他文本。这是在 DataFrame 级别解决此问题的标准方法。