首页 > 解决方案 > 使用 Python Great Expectations 删除无效数据

问题描述

我刚开始使用 Great Expectations 库,我想知道是否可以使用它从 Pandas DataFrame 中删除无效数据。如果可能的话,我该怎么做?我还想将无效数据插入 PostgreSQL 数据库。

我在文档和网络搜索中没有找到任何关于此的内容。

稍后编辑:澄清:我需要在这种情况下,例如在 DataFrame 中找到 5 行无效的行(例如 df.expect_column_values_to_not_be_null('age') 有 5 行为 null)从原始 DataFrame 中删除它们并插入它们在 PostgreSQL 错误表中

标签: pythonpandaspostgresqlgreat-expectations

解决方案


Great Expectations是验证数据的强大工具。
像所有强大的工具一样,它并不是那么简单。

你可以从这里开始:

import great_expectations as ge
import numpy as np
import pandas as pd
    
# get some random numbers and create a pandas df
df_raw = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

# initialize a "great_expectations" df 
df = ge.from_pandas(df_raw)

# search for invalidate data on column 'A'. 
# In this case, i'm looking for any null value from column 'A'.
df.expect_column_values_to_not_be_null('A')

结果:

{
  "exception_info": null,
  "expectation_config": {
    "expectation_type": "expect_column_values_to_not_be_null",
    "kwargs": {
      "column": "A",
      "result_format": "BASIC"
    },
    "meta": {}
  },
  "meta": {},
  "success": true,
  "result": {
    "element_count": 100,
    "unexpected_count": 0,
    "unexpected_percent": 0.0,
    "partial_unexpected_list": []
  }
}

看看回复:好消息!!!
我的df中没有null值。 "unexpected_count"等于0

API 参考: https ://legacy.docs.greatexpectations.io/en/latest/autoapi/great_expectations/index.html


编辑: 如果您只需要找到一些无效值并将您的 df 拆分为:

  1. 清洁数据框
  2. 脏数据框

也许你不需要"great_expectations"。你可以使用这样的函数:

import pandas as pd

my_df = pd.DataFrame({'A': [1,2,1,2,3,0,1,1,5,2]})

def check_data_quality(dataframe):
    df = dataframe
    clean_df = df[df['A'].isin([1, 2])]
    dirty_df = df[df["A"].isin([1, 2]) == False]
    return {'clean': clean_df, 
            'dirty': dirty_df}

my_df_clean = check_data_quality(my_df)['clean']
my_df_dirty = check_data_quality(my_df)['dirty']

推荐阅读