【问题标题】:Display row with False values in validated pandas dataframe column [duplicate]在经过验证的 pandas 数据框列中显示具有 False 值的行 [重复]
【发布时间】:2021-05-09 02:08:29
【问题描述】:

我正在验证数据框中的“价格”列。示例:

    ArticleId   SiteId  ZoneId  Date       Quantity Price   CostPrice
53  194516      9          2    2018-11-26  11.0    40.64   27.73
164 200838      9          2    2018-11-13  5.0     99.75   87.24
373 200838      9          2    2018-11-27  1.0     99.75   87.34
pd.to_numeric(df_sales['Price'], errors='coerce').notna().value_counts()

我很想用 False 值显示这些行,这样我就知道它们有什么问题。我该怎么做?

True     17984
False       13
Name: Price, dtype: int64

谢谢。

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您可以在价格isnull()时打印您的行:

    print(df_sales[df_sales['Price'].isnull()])
    
       ArticleId  SiteId  ZoneId       Date  Quantity  Price  CostPrice
    1     200838       9       2 2018-11-13         5    NaN     87.240
    

    【讨论】:

      【解决方案2】:
      • pd.to_numeric(df['Price'], errors='coerce').isna() 返回一个Boolean,可用于选择导致错误的行。
        • 这包括NaN 或带有strings 的行
      import pandas as pd
      
      # test data
      df = pd.DataFrame({'Price': ['40.64', '99.75', '99.75', pd.NA, 'test', '99. 0', '98 0']})
      
         Price
      0  40.64
      1  99.75
      2  99.75
      3   <NA>
      4   test
      5  99. 0
      6   98 0
      
      # find the value of the rows that are causing issues
      problem_rows = df[pd.to_numeric(df['Price'], errors='coerce').isna()]
      
      # display(problem_rows)
         Price
      3   <NA>
      4   test
      5  99. 0
      6   98 0
      

      另类

      • 创建一个额外的列,然后用它来选择问题行
      df['Price_Updated'] = pd.to_numeric(df['Price'], errors='coerce')
      
         Price  Price_Updated
      0  40.64          40.64
      1  99.75          99.75
      2  99.75          99.75
      3   <NA>            NaN
      4   test            NaN
      5  99. 0            NaN
      6   98 0            NaN
      
      # find the problem rows
      problem_rows = df.Price[df.Price_Updated.isna()]
      

      说明

      • 使用.to_numeric() 更新列,然后检查NaNs 不会告诉您为什么必须强制行。
      # update the Price row 
      df.Price = pd.to_numeric(df['Price'], errors='coerce')
      
      # check for NaN
      problem_rows = df.Price[df.Price.isnull()]
      
      # display(problem_rows)
      3   NaN
      4   NaN
      5   NaN
      6   NaN
      Name: Price, dtype: float64
      

      【讨论】:

        猜你喜欢
        • 2021-06-13
        • 2019-04-02
        • 2022-01-14
        • 2018-07-07
        • 2016-06-01
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-06
        相关资源
        最近更新 更多