Обнаружение и регистрация неисправного условия проверки в пандах - PullRequest
0 голосов
/ 21 ноября 2018

У меня есть датафрейм df,

      plan_year                                    name metal_level_name
0        20118            Gold Heritage Plus 1500 - 02             Gold
1         2018                                     NaN         Platinum
2         2018            Gold Heritage Plus 2000 - 01             Gold

Я поставил проверку данных в столбцы plan_year и name, как показано ниже,

m4 = ((df['plan_year'].notnull()) & (df['plan_year'].astype(str).str.isdigit()) & (df['plan_year'].astype(str).str.len() == 4))

m1 = (df1[['name']].notnull().all(axis=1))

Я получаю действительныйкадр данных с ниже,

df1 = df[m1 & m4]

Я могу получить строки, которых нет в df1 (строки, которые являются недопустимыми)

merged = df.merge(df1.drop_duplicates(), how='outer', indicator=True)
merged[merged['_merge'] == 'left_only']

Я хочу отслеживать, какая строка не удаласьиз-за какой проверки.

Я хочу получить кадр данных со всеми недопустимыми данными, который будет выглядеть примерно так:

 plan_year                                    name metal_level_name    Failed message
0        20118            Gold Heritage Plus 1500 - 02             Gold    Failed due to wrong plan_year
1         2018                                     NaN         Platinum     name column cannot be null

Может кто-нибудь помочь мне с этим, пожалуйста.

1 Ответ

0 голосов
/ 21 ноября 2018

Вы можете использовать numpy.select с инвертированием логических масок на ~:

message1 = 'name column cannot be null'
message4 = 'Failed due to wrong plan_year'


df['Failed message'] = np.select([~m1, ~m4], [message1, message4], default='OK')
print (df)
   plan_year                          name metal_level_name  \
0      20118  Gold Heritage Plus 1500 - 02             Gold   
1       2018                           NaN         Platinum   
2       2018  Gold Heritage Plus 2000 - 01             Gold   

                  Failed message  
0  Failed due to wrong plan_year  
1     name column cannot be null  
2                             OK  

df1 = df[df['Failed message'] != 'OK']
print (df1)
   plan_year                          name metal_level_name  \
0      20118  Gold Heritage Plus 1500 - 02             Gold   
1       2018                           NaN         Platinum   

                  Failed message  
0  Failed due to wrong plan_year  
1     name column cannot be null  

РЕДАКТИРОВАТЬ: Для нескольких сообщений об ошибках создать новый DataFrameна concat, а затем умножить его на имена столбцов с разделителем на dot и в последний раз удалить разделитель с правой стороны на rstrip:

print (df)
   plan_year                          name metal_level_name
0      20118  Gold Heritage Plus 1500 - 02             Gold
1       2018                           NaN         Platinum
2       2018  Gold Heritage Plus 2000 - 01             Gold
1      20148                           NaN         Platinum

message1 = 'name column cannot be null'
message4 = 'Failed due to wrong plan_year'

df1 = pd.concat([~m1, ~m4], axis=1, keys=[message1, message4])
print (df1)
   name column cannot be null  Failed due to wrong plan_year
0                       False                           True
1                        True                          False
2                       False                          False
1                        True                           True


df['Failed message'] = df1.dot(df1.columns + ', ').str.rstrip(', ')
print (df)

   plan_year                          name metal_level_name  \
0      20118  Gold Heritage Plus 1500 - 02             Gold   
1       2018                           NaN         Platinum   
2       2018  Gold Heritage Plus 2000 - 01             Gold   
1      20148                           NaN         Platinum   

                                      Failed message  
0                      Failed due to wrong plan_year  
1                         name column cannot be null  
2                                                     
1  name column cannot be null, Failed due to wron...  

df1 = df[df['Failed message'] != '']
print (df1)
   plan_year                          name metal_level_name  \
0      20118  Gold Heritage Plus 1500 - 02             Gold   
1       2018                           NaN         Platinum   
1      20148                           NaN         Platinum   

                                      Failed message  
0                      Failed due to wrong plan_year  
1                         name column cannot be null  
1  name column cannot be null, Failed due to wron...  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...