【问题标题】:Display values that does not end with ".0" Python Pandas显示不以“.0”结尾的值 Python Pandas
【发布时间】:2017-02-07 11:34:14
【问题描述】:

我有一个包含 NaN 值和浮点值的浮点列。如何过滤掉那些不以.0 结尾的值?

例如:

Col1
0.7
1.0
1.1
9.0
9.5
NaN

希望的结果是:

Col1
0.7
1.1 
9.2

【问题讨论】:

    标签: python pandas indexing conditional-statements nan


    【解决方案1】:

    你可以使用boolean indexing:

    #convert to string and compare last value
    print ((df.Col1.astype(str).str[-1] != '0') & (df.Col1.notnull()))
    0     True
    1    False
    2     True
    3    False
    4     True
    5    False
    Name: Col1, dtype: bool
    
    print (df[(df.Col1.astype(str).str[-1] != '0') & (df.Col1.notnull())])
       Col1
    0   0.7
    2   1.1
    4   9.5
    

    将转换后的值与ìnt 进行比较的另一种解决方案,但首先需要fillna

    s = df.Col1.fillna(1)
    print (df[s.astype(int) != s])
       Col1
    0   0.7
    2   1.1
    4   9.5
    

    时间安排

    #[30000 rows x 1 columns]
    df = pd.concat([df]*10000).reset_index(drop=True)
    
    def jez2(df):
        s = df.Col1.fillna(1)
        return (df[s.astype(int) != s])
    
    In [179]: %timeit (df[(df.Col1.astype(str).str[-1] != '0') & (df.Col1.notnull())])
    10 loops, best of 3: 80.2 ms per loop
    
    In [180]: %timeit (jez2(df))
    1000 loops, best of 3: 1.16 ms per loop
    
    In [181]: %timeit (df[df.Col1 // 1 != df.Col1].dropna())
    100 loops, best of 3: 3.04 ms per loop
    
    In [182]: %timeit (df[df['Col1'].mod(1) > 0].dropna())
    100 loops, best of 3: 2.58 ms per loop
    

    【讨论】:

      【解决方案2】:

      使用//除法

      df[df.Col1 // 1 != df.Col1].dropna()
      

      【讨论】:

        【解决方案3】:

        另一种方法是使用mod(1)计算与1的模数:

        In [60]:
        df[df['Col1'].mod(1) > 0].dropna()
        
        Out[60]:
           Col1
        0   0.7
        2   1.1
        4   9.5
        

        这里我们看到mod 的效果,整数变为0,而小数部分将保留:

        In [62]:
        df['Col1'].mod(1)
        
        Out[62]:
        0    0.7
        1    0.0
        2    0.1
        3    0.0
        4    0.5
        5    NaN
        Name: Col1, dtype: float64
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-27
          • 1970-01-01
          • 2019-11-28
          • 1970-01-01
          • 2014-12-01
          • 1970-01-01
          • 2021-01-07
          • 1970-01-01
          相关资源
          最近更新 更多