清理Excel文档-根据其内容格式化单元格

时间:2019-10-11 13:19:52

标签: python pandas

在Python中相当新,并完成了我的第一个项目-excel数据清理。 这个想法是在将数据上传到系统之前检查数据。不符合要求的单元格必须突出显示,并在“评论”列中添加评论。

检查要求:

  1. 标记包含数字/符号的名字或姓氏-操作:突出显示单元格并在注释列中添加注释

  2. 检查空白单元格-操作:突出显示该单元格并添加评论

我尝试了不同的方式(特别是使用IF语句)来突出显示不符合要求的单元格并同时进行注释,但是没有任何效果:(希望得到一些支持

import pandas as pd
import numpy as np

df_i = pd.DataFrame({'Email' : ['john@yahoo.com','john@outlook.com','john@gmail.com'], 'First Name': ['JOHN','   roman2   ',''], 'Last Name': ['Smith','','132'], 'Comments':['','','']})
emails_to_exclude = ('@gmail', '@yahoo')

print(df_i)

#Proper names
def proper_name(name):
    return name.str.title()

df_i['First Name'] = proper_name(df_i['First Name'] )
df_i['Last Name'] = proper_name(df_i['Last Name'] )

#Trim spaces
def trim(cell):
        return cell.apply(lambda x: x.str.strip())

df_i = trim(df_i)

#Check public email domains
df_i.loc[df_i['Email'].str.contains('|'.join(emails_to_exclude), case=False),'Comments'] = df_i['Comments'].astype(str) + 'public email domain'

#Check first and last name

list_excl = ["1","2","3","4","5","6","7","8","9","0"]
df_i.loc[df_i['First Name'].str.contains('|'.join(list_excl), case=False), 'Comments']  = df_i['Comments'].astype(str) + " Check 'First Name'"
df_i.loc[df_i['Last Name'].str.contains('|'.join(list_excl), case=False), 'Comments']  = df_i['Comments'].astype(str) + " Check 'Last Name'"

print(df_i)

1 个答案:

答案 0 :(得分:0)

我将编写一个使用re的函数来查看字符串是否与定义的模式匹配。我知道所需的模式是由大小写字母组成的序列(不确定名称是否可以包含空格字符)。

对于格式部分,请使用df.style。基本上,您编写了一个函数,该函数定义了如何使用CSS格式化每个单元格。您将需要导出到excel(csv不包含有关格式的任何信息)。您也可以将其呈现为html表。 Read more。请注意,在使用df.style之后,您正在使用的对象不再是pd.DataFrame。而是pandas.io.formats.style.Styler。在对数据框进行样式设置之前,应该对其进行任何操作

import pandas as pd
import numpy as np
import re

def highlight_invalid(string, invalid_colour='yellow', empty_colour='red'):
    if string:
        # The string contains only one or more letters
        pattern = re.compile(r'^([A-z])+$')
        if pattern.match(string):
            # do not highlight valid strings
            return ''
        else:
            # highlight non-matching strings in invalid_colour
            return f'background-color: {invalid_colour}'
    else:
        # highlight empty strings in empty_colour
         return f'background-color: {empty_colour}'

cols = ['First Name', 'Last Name']
for col in cols:
    # It didn't work when I tried it with missing values, so make sure to replace
    df_i[col] = df_i[col].replace(np.nan, '')

# Apply the highlighting function to every cell of 'First Name' and 'Last Name'
df_i = df_i.style.applymap(highlight_invalid, subset=cols)

df_i.to_excel(fname)

也许您想编写一个单独的函数来进行数据验证,并将其用于突出显示和添加注释。我将把它留给您,因为这与格式化本身无关,应该作为一个单独的问题提出来。