【问题标题】:How to manipulate value in each index?如何操纵每个索引中的值?
【发布时间】:2020-04-22 00:00:10
【问题描述】:

我有一列有数字。它有大约 60000 个索引。一些索引的值如 1.000 或 5.0 或 2323.0000 或 1.446 这些索引的正确值是 1、5、2323、1446。换句话说,我有两种情况。对于第一种情况,如果索引是带有点和该点之后的零的数值,我需要删除该点和该点之后的所有零。第二种情况是索引具有带点的数值,但点后的数字不为零。我只需要摆脱点。我将如何做到这一点?

【问题讨论】:

    标签: python pandas numpy data-manipulation data-cleaning


    【解决方案1】:

    我认为你需要:

    df = pd.DataFrame({'a':range(5)}, index=[1.0,5.0,2323.0,1.446,10.5])
    print (df)
              a
    1.000     0
    5.000     1
    2323.000  2
    1.446     3
    10.500    4
    

    df.index = df.index.map(lambda x: int(x) if x.is_integer() else int(x * 1000))
    

    或者:

    df.index = np.where(df.index.astype(int) == df.index,df.index, df.index * 1000).astype(int)
    

    print (df)
           a
    1      0
    5      1
    2323   2
    1446   3
    10500  4
    

    或者可能需要:

    df.index = df.index.astype(str).str.replace('\.0','').str.replace('.','').astype(int)
    print (df)
          a
    1     0
    5     1
    2323  2
    1446  3
    105   4
    

    【讨论】:

    • 如果数字没有3位小数怎么办?
    【解决方案2】:

    要检查值是否为整数,请检查How to check if a float value is a whole number

    如果不是,您可以乘以 then 直到它是。之后,您可以在这两种情况下强制转换为 int。

    【讨论】:

      【解决方案3】:

      这可能不是最优雅的解决方案,但它简单干净,没有导入和其他东西,只是基本的 python

      outcome = []
      for i in raw:
          if i%1 == 0: # check if number is whole
              outcome += int(i) # append normally as int
          else:
              outcome += int(str(i).replace('.','')) #replace .
      return outcome
      

      可能是

      return [(int(i) if i.is_integer() else int(str(i).replace('.',''))) for i in raw]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 2019-12-06
        • 2022-01-04
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多