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

标签 python pandas

Python 中的新手,正在做我的第一个项目 - excel 数据清理。 这个想法是在将数据上传到系统之前检查数据。不符合要求的单元格必须突出显示,并在comment栏中添加注释。

检查要求:

  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)

最佳答案

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

对于格式部分,请使用df.style。基本上,您编写一个函数来定义如何使用 CSS 设置每个单元格的格式。您需要导出到 Excel(csv 不包含任何有关格式的信息)。您还可以将其呈现为 html 表格。 Read more 。请注意,使用df.style后,您使用的对象不再是pd.DataFrame。相反,它是pandas.io.formats.style.Styler。在设置 DataFrame 样式之前,您应该对 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)

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

关于python - 清理 Excel 文档 - 根据其内容格式化单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342170/

相关文章:

python - 将 MySQL 表数据转储到 csv 并转换字符编码的最佳方法是什么?

python - 如何在 python 中对列范围求和

python - 如何修复原子编辑器中的 `flake8 D100 — Missing docstring` 错误

python - 如何在Python中创建一个可以通过PIP安装的CLI?

python - 无法使用 vlc python 绑定(bind)播放文件

python - pandas 选择数据透视表的子集

python - 分组数据和搜索值集

python - DatetimeIndex 仅用于 pandas 中的每日数据

python - 使用 travis 和 heroku 进行持续部署——保留某种状态

python - 这个异步 aiohttp 代码有什么问题?