【问题标题】:Strip trailing decimal points from floats in pandas从 pandas 中的浮点数中去除尾随小数点
【发布时间】:2017-08-25 12:43:41
【问题描述】:

我的数据集中的所有列似乎都是浮点数。 有些包含像'20这样的值。 '或'11。 '

如何有选择地快速删除点和空格,而不影响列中的其他值,例如“24.4”或“12.5”?

我尝试了几种解决方案,但都没有奏效。

我的目标是改变,例如 '12. ' 到 '12',对于每个单元格中的每个值,其中 '. ' 出现。

【问题讨论】:

  • 我非常怀疑情况是否如此,但如果您能向我们展示您的数据,那将会有所帮助。

标签: python pandas datagram


【解决方案1】:

可以为pandas设置自定义的float格式化函数,例如:

>>> import pandas as pd
>>> df = pd.DataFrame({'col1':[1, 2, 3], 'col2':[2.0, 1.0, 4.1]})
>>> pd.set_option('display.float_format', lambda x: ('%f' % x).rstrip('.0'))
>>> df
   col1  col2
0     1     2
1     2     1
2     3   4.1

【讨论】:

    【解决方案2】:

    您可以使用正则表达式来替换 ie

    df.replace('\.(?!\d)','',regex=True) 
    

    如果您有类似的数据框。

    df = pd.DataFrame(['12.','13.','14.1','15.5'])
    df.replace('\.(?!\d)','',regex=True) # inplace = True if you want to change main dataframe.
    
     0
    0 12
    1 13
    2 14.1
    3 15.5
    

    【讨论】:

    • 它们不是字符串,而是浮点数。
    • 他说'快点去掉点和空格',我希望可能是字符串
    【解决方案3】:

    如果您的列包含字符串:

    >>> a
       0     1
    0  1  12. 
    1  2  14.5
    2  3  15. 
    3  4  16.3
    >>> a[1]=[i.replace('. ', '') for i in a[1]]
    >>> a
       0     1
    0  1    12
    1  2  14.5
    2  3    15
    3  4  16.3
    

    如果有浮点数,您可以创建一个混合类型(int 和浮点数)的新列表:

    >>> b=[int(i) if i.is_integer() else float(i) for i in a[1]]
    >>> b
    [12, 14.5, 15, 16.3]
    

    但你不能在数据框中这样做:

    >>> a[1]=[int(i) if i.is_integer() else float(i) for i in a[1]]
    >>> a
         0     1
    0  1.0  12.0
    1  2.0  14.5
    2  3.0  15.0
    3  4.0  16.3
    

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2014-11-05
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2011-08-03
      • 2018-11-15
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多