Python相当新,并完成了我的第一个项目-excel数据清理。这个想法是在将数据上传到系统之前检查数据。不符合要求的单元格必须突出显示,并在该comment
列中添加注释。
检查要求:
标记包含数字/符号的名字或姓氏-操作:突出显示单元格并在注释列中添加注释
检查空白单元格-操作:突出显示该单元格并添加评论
我尝试了不同的方式(尤其是使用IF语句)来突出显示不符合要求的单元格并同时进行注释,但没有任何效果
import pandas as pd
import numpy as np
df_i = pd.DataFrame({'Email' : ['[email protected]','[email protected]','[email protected]'], '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)
我将编写一个函数re
来查看字符串是否与定义的模式匹配。我知道所需的模式是大写或小写字母的序列(不确定名称是否可以包含空格字符)。
对于格式部分,请使用df.style
。基本上,您编写了一个函数,该函数定义了如何使用CSS格式化每个单元格。您将需要导出到excel(csv不包含有关格式的任何信息)。您也可以将其呈现为html表。阅读更多。请注意,使用后df.style
,您正在使用的对象将不再存在pd.DataFrame
。而是pandas.io.formats.style.Styler
。在对DataFrame进行样式设置之前,您应该执行任何您想做的事情。
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)
也许您想编写一个单独的函数来进行数据验证,并将其用于突出显示和添加注释。我将把它留给您,因为这与格式化本身无关,应该作为一个单独的问题提出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句