代码之家  ›  专栏  ›  技术社区  ›  Aaron N. Brock

在字符串和浮点的数据帧中,将浮点转换为整数,然后转换为字符串

  •  -1
  • Aaron N. Brock  · 技术社区  · 6 年前

    我有以下数据帧的数据类型 object :

      col1 col2  col3
    0  1.1  3.3  spam
    1  2.2  foo  eggs
    2  bar  4.4   5.5
    

    string :

      col1 col2  col3
    0    1    3  spam
    1    2  foo  eggs
    2  bar    4     5
    

    errors = 'ignore' ,似乎忽略了整件事)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Jon Clements    6 年前

    可以使用助手函数:

    • 尝试将对象中的内容转换为 float 函数可以解释为 浮动 但是“你好。你好吗?”不会。。。
    • 然后试着去转换 浮动 到一个 int
    • 然后返回其 str 价值

    浮动 int(some_float) str公司

    如:

    def try_to_int(obj):
        try:
            return str(int(float(obj)))
        except (ValueError, TypeError):
            return obj
    

    然后用它和 new_df = df.applymap(try_to_int)

        2
  •  2
  •   James    6 年前

    一种方法是强制转换为字符串,然后使用正则表达式删除小数。

    import pandas as pd
    
    df = pd.DataFrame({'col1': [1.1, 2.2, 'bar'], 
                       'col2': [3.3, 'foo', 4.4], 
                       'col3': ['spam', 'eggs', 5.5]})
    
    df = df.astype(str).replace(r'(\-?\d+)\.\d+', r'\1', regex=True)
    
    # returns:
      col1 col2  col3
    0    1    3  spam
    1    2  foo  eggs
    2  bar    4     5