验证熊猫数据框列

我有一个列如下的数据框 -

u'wellthie_issuer_identifier', u'issuer_name', u'service_area_identifier', u'hios_plan_identifier', u'plan_year', u'type'

我需要验证每一列中的值,最后有一个有效的数据框。

例如,我需要检查plan_year列是否满足以下验证

presence: true, numericality: true, length: { is: 4 }

hios_plan_identifier 列满足以下正则表达式。

          format: /\A(\d{5}[A-Z]{2}[a-zA-Z0-9]{3,7}-TMP|\d{5}[A-Z]{2}\d{3,7}(\-?\d{2})*)\z/,
          presence: true, length: { minimum: 10 },

type 列包含,

in: ['MetalPlan', 'MedicarePlan', 'BasicHealthPlan', 'DualPlan', 'MedicaidPlan', 'ChipPlan']

有很多列需要验证。我试图给出一个示例数据。

我可以用 s 检查正则表达式tr.contains('\A(\d{5}[A-Z]{2}[a-zA-Z0-9]{3,7}-TMP|\d{5}[A-Z]{2}\d{3,7}(\-?\d{2})*)\Z', regex=True)

同样,我也可以单独检查其他验证。我对如何将所有验证放在一起感到困惑。我应该把所有的都放在一个有条件的if循环中and吗?有没有一种简单的方法来验证数据框列?在这里需要帮助


qq_笑_17
浏览 145回答 1
1回答

牛魔王的故事

您可以使用多种 Pandas 函数。基本上,您可以用来按内容过滤数据框的语法是:df = df[(condition1) & (condition2) & ...] # filter the df and assign to the same df专门针对您的情况,您可以替换condition为以下函数(表达式):df[some_column] == some_value df[some_column].isin(some_list_of_values) # This check whether the value of the column is one of the values in the listdf[some_column].str.contains() # You can use it the same as str.contains()df[some_column].str.isdigit() # Same usage as str.isdigit(), check whether string is all digits, need to make sure column type is string in advancedf[some_column].str.len() == 4 # Filter string with length of 4最后,如果要重置索引,可以使用df = df.reset_index(drop=True)将输出 df 索引重置为 0,1,2,...编辑:要检查您可以使用的 NaN、NaT、None 值df[some_column].isnull()对于多列,您可以使用df[[col1, col2]].isin(valuelist).all(axis=1)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python