我想使用
.CSV
函数在 highlight_special
文件中添加突出显示特定单元格。
代码在终端中运行,没有任何异常,但是当我查看
.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')
当你拨打
highlight_special()
时,siders
仍然是空的。
你必须先调用你的方法special()
。
highlight_special
也被滥用(参见这里),并且它在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()