【发布时间】:2016-12-14 21:24:33
【问题描述】:
谁能解释一下这个函数在做什么?就像我知道它检查 csv 中的一行是否重复。但是,我只想检查特定列是否具有重复值。我怎么做?
@Validator
def hasDuplicates( fileInDf, fileType = File_Name_All, kwargs = def_kwargs ):
''' Return row indexes that are duplicates '''
import pandas
if fileInDf is None:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Input File is not a valid file for rule : hasDuplicates' )
if type( fileInDf ) is not pandas.DataFrame:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Type %s is not a valid DataFrame Type for rule : hasDuplicates' % type( fileInDf ))
if fileInDf.empty:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Input File is not a valid file for rule : hasDuplicates' )
dups = fileInDf.duplicated()
indexes = dups[ dups == True ].index.tolist()
fixedDf = fileInDf.drop_duplicates()
ret = Rule_Decision.FAILED if len( fixedDf ) != len( fileInDf ) else Rule_Decision.SUCCESS
return ValidatorResponse( rule_decision = ret, rule_return_fixedDf = fixedDf, rule_return_val = indexes )
更新:
@Validator
def hasDuplicatesSingleColumn( val, fileInDf, fileType = File_Name_All, kwargs = def_kwargs ):
''' Return row indexes that are duplicates '''
import pandas
if fileInDf is None:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Input File is not a valid file for rule : hasDuplicates' )
if type( fileInDf ) is not pandas.DataFrame:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Type %s is not a valid DataFrame Type for rule : hasDuplicates' % type( fileInDf ))
if fileInDf.empty:
return ValidatorResponse( rule_decision = Rule_Decision.INVALID_INPUT, rule_return_message = 'Input File is not a valid file for rule : hasDuplicates' )
col_dups = fileInDf[['column']].duplicated()
indexes = col_dups[ col_dups == True ].index.tolist()
new_df = fileInDf[['column']].drop_duplicates()
ret = Rule_Decision.FAILED if len( new_df ) != len( fileInDf ) else Rule_Decision.SUCCESS
return ValidatorResponse( rule_decision = ret, rule_return_fixedDf = new_df, rule_return_val = indexes )
但是,我如何获取索引?上述函数中的方式是否正确?
【问题讨论】:
-
你能提供一些上下文吗?
Validator和ValidatorResponse之类的东西从何而来?除了 Pandas,您还在使用特定的包吗?
标签: python csv pandas dataframe