Python 清理excel文档-基于内容格式化单元格
Python非常新,正在执行我的第一个项目—excel数据清理。 这个想法是在上传数据到系统之前检查数据。必须突出显示不符合要求的单元格,并将注释添加到Python 清理excel文档-基于内容格式化单元格,python,pandas,Python,Pandas,Python非常新,正在执行我的第一个项目—excel数据清理。 这个想法是在上传数据到系统之前检查数据。必须突出显示不符合要求的单元格,并将注释添加到comment列中 检查要求: 标记包含数字/符号的名字或姓氏-操作:突出显示单元格并向注释列添加注释 检查空单元格-操作:突出显示单元格并添加注释 我尝试了不同的方法(特别是使用IF语句)来突出显示不符合要求的单元格,并同时进行注释,但没有任何效果 import pandas as pd import numpy as np df_i = p
comment
列中
检查要求:
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)
我将编写一个函数,使用
re
查看字符串是否与定义的模式匹配。我知道所需的模式是一系列大写或小写字母(不确定名称是否可以包含空格字符)
对于格式化部分,请使用df.style
。基本上,您可以编写一个函数来定义如何使用CSS格式化每个单元格。您需要导出到excel(csv不包含任何有关格式的信息)。也可以将其呈现为html表。请注意,在使用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)
也许您想编写一个单独的函数来进行数据验证,并在突出显示和添加注释时使用它。我将把这个问题留给您,因为这与格式本身无关,应该作为一个单独的问题提问。您好,突出显示单元格是什么意思?您好,我的意思是更改单元格颜色(背景色)