【问题标题】:Pandas dataframe replace digits after N decimals to empty stringPandas数据框将N个小数后的数字替换为空字符串
【发布时间】: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

标签: python pandas


【解决方案1】:

你可以试试这个模式:

df1 = df1.replace(r"^(\d+\.\d{," + rf"{round_}" + r'})(\d*)',r'\1',regex=True)

输出:

      survived pclass    age  sibsp  parch    fare
count    891.0  891.0  714.0  891.0  891.0   891.0
mean      0.38   2.30  29.69   0.52   0.38   32.20
std       0.48   0.83  14.52   1.10   0.80   49.69
min        0.0    1.0   0.42    0.0    0.0     0.0
25%        0.0    2.0  20.12    0.0    0.0    7.91
50%        0.0    3.0   28.0    0.0    0.0   14.45
75%        1.0    3.0   38.0    1.0    0.0    31.0
max        1.0    3.0   80.0    8.0    6.0  512.32

【讨论】:

  • 抱歉,我刚刚意识到它使 12.349 ==> 12.34 而不是 12.349 ==> 12.35。对于 XY 问题,我很抱歉。
【解决方案2】:

我认为您只需将df1.B 转换为浮动并将mapf-string 一起使用

s = df1.B.astype(float).map(lambda x: f'{x:.02f}')

Out[8]:
0    12.35
1    12.22
Name: B, dtype: object

【讨论】:

    【解决方案3】:

    一种方法是乘以 100,转换为 int 并除以 100:

    import pandas as pd
    
    df1 = pd.DataFrame({'A': ['hello','wold'],
                       'B': [12.346789, 12.223344]})
    
    df1['B'] = (df1.B * 100).astype(int) / 100
    
    print(df1)
    

    打印:

           A      B
    0  hello  12.34
    1   wold  12.22
    

    【讨论】:

      【解决方案4】:

      假设您以字符串开头,您可以将列转换为数字并使用 round() 仅保留 2 位数字。

      import pandas as pd
      
      df = pd.DataFrame({'A': ['hello','wold'],
                     'B': ['12.346789', '12.223344']})
      
      df["B"] = round(pd.to_numeric(df["B"]),2)
      
      print(df) 
      

      输出:

      A      B
      0  hello  12.35
      1   wold  12.22
      

      如果您已经有一列数字,那么您只需要这个。

      df["B"] = round(df["B"],2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-11
        • 2018-02-03
        • 2021-05-13
        • 1970-01-01
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        相关资源
        最近更新 更多