python - 验证 Pandas 数据框列

标签 python pandas

我有一个包含以下列的数据框 -

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']

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

我可以使用 str.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 循环中。有没有一种简单的方法来验证数据框列?在这里需要帮助

最佳答案

您可以使用多个 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 list
df[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 advance
df[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)

关于python - 验证 Pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293913/

相关文章:

python - GQL 错误报告属性未在 dev_appserver 上建立索引?

python - mongoengine 默认超时配置

Python Pandas - 检查一个值是否在前 n 行

python - 仅查找列表中的唯一坐标

python - 散点矩阵中的多个数据

python - Pandas - 如何从 Dataframe 中删除引号

python Pandas : Create Column That Acts As A Conditional Running Variable

python - 如何根据日期列更改线图的颜色?

python - Pandas:基于标题子字符串的部分枢轴

python - 将元素附加到数组列表(以最简洁的惯用方式)