csv 通过pandas为Excel中的某些单元格添加颜色- python

flseospp  于 2023-11-14  发布在  Python
关注(0)|答案(1)|浏览(158)

我想使用highlight_special函数在.CSV文件中添加突出显示特定单元格。
代码在终端中运行,没有任何例外,但当我查看.CSV时,它保持不变
这段代码获取一个csv文件,运行它来查看是否有任何带有特殊字符的单词,如果有,它会将主题添加到siders列表中。
然后迭代siders列表,以突出显示包含siders列表中文本的单元格。
先谢了。

import pandas as pd
#import numpy as np 4 LATER
import os

# get the file path
dfile = input("please enter the name of the file you wish ro analyse plus the type(.csv/.xls/.bat): ")
dfile = os.getcwd() + "\\" + dfile
# list of the words with the special letters
siders = []
# special letters list
special_characters = ["\\", ",", "-", "_", "+", ".", "?", "\\", "#", "*", "&", "!", "'", "\""]

# analasys function
def special(data, filter_col):
    # loads the file as a csv
    global datafile
    datafile = pd.read_csv(data)
    # iterates the file line by line plus stating the number of line
    for row, i in datafile.iterrows():
        # tlowercase the column indicated by [filter_col
        lowi = str(i[filter_col]).lower()
        # looks for a special letter in lowi stated..
        for chr in special_characters:
            if chr in lowi:
                siders.append(lowi)  # adds the words with special letters to a side list
                print("succes special character {} found in row {}".format(chr, str(row)))
            else:
                continue
                # print("{} no special chars where found".format(str(row)))
    count = 0
    for index, word in enumerate(siders):
        count += 1
        print(str(index) + " " + word + "\n ")  # prints the special woprds
    print("count of words that need manual review is: {}".format(count))

def highlight_special(cells):  # cells=datafile
    for each in cells:
        if each in siders:
            return ['background_color: yellow']
        else:
            return ['background_color: white']
    datafile.style.apply(highlight_special, axis=1)

def duplicants(datafile):
    pass

highlight_special(dfile)
special(dfile, 'Account Name')

字符串

lfapxunr

lfapxunr1#

当你调用highlight_special()时,siders仍然是空的。你必须在之前调用你的方法special()
highlight_special也被误用(参见here),它在datafile.style.apply中调用自己。
另外,你正在使用全局变量,并在函数中设置它们。除非你这样做,否则它不会工作(参见doc):

x = ""
def myfunc():
  global x
  x = "fantastic"

myfunc()

字符串
下面是一个使用applymap为excel文件着色的工作示例

siders = [1]

df = pd.DataFrame([{'value': 1, "value_2": 913}])
def highlight_cells(value):
    color = "yellow" if value in siders else "white"
    return f"background-color: {color}"

writer = pd.ExcelWriter(f"/tmp/test.xlsx", engine="xlsxwriter")
df2 = df.style.applymap(highlight_cells)
df2.to_excel(writer)
writer.save()

相关问题