【发布时间】:2020-06-24 18:45:58
【问题描述】:
我正在学习如何在 pandas 数据框替换中使用正则表达式。我遇到了以下问题:
我正在尝试将 N 个小数点后的字符串替换为空。
例如12.349 ==> 12.35。
MWE
import numpy as np
import pandas as pd
import seaborn as sns
df1 = pd.DataFrame({'A': ['hello','wold'],
'B': [12.346789, 12.223344]})
df1 = df1.astype(str)
round_ = 2
to_replace = r"(^\d+\." + r"\d" * round_ + r")(.*)"
repl = lambda m: m.group(0)
df1 = df1.replace(to_replace,repl,regex=True)
df1
Pandas 文档说我可以使用正则表达式来替换字符串,但是当我使用它时,我得到了函数 repr 而不是值。 问题如何解决?
更新
我试图将格式应用于数据帧的转置。 (当然我可以在转换之前设置样式,但由于某些原因我需要应用格式来转置)。
df1 = pd.DataFrame({'A': ['hello','wold'],
'B': [12.349, 12.22]})
df1 = df1.T
df1.style.format({'B': "{:.2f}"}, axis=0)
参考文献
【问题讨论】:
-
@ALollz,是的,我试图将
style.format(fmt)用于数据框的行,但我无法将格式应用于行,只能将其应用于列。所以我尝试首先将数据框设为字符串类型并进行字符串操作以删除多余的小数点。 -
我想你想要
round(2).astype(str),不是吗?您不能使用正则表达式将12.349更改为12.35。