通过熊猫-python

时间:2020-09-29 14:43:25

标签: python excel pandas csv cell

我想使用 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)
    # itterates 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')

1 个答案:

答案 0 :(得分:0)

当您致电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()
相关问题