如何根据单元格值对列中的单元格进行着色?

发布于 01-14 06:12 字数 951 浏览 3 评论 0原文

我正在尝试将大型 XLSX 文件的指定列中的单元格着色为红色,具体取决于 U 列中的值是否为“N”。

我可以使用下面的代码实现此目的,但需要 20 多分钟,有人可以建议我如何提高性能以使运行速度更快吗?

import pandas as pd
import time

startTime = time.time()

filePath = r"C:\\Users\\Desktop\\Match\\"
parameters = 'large_file.xlsx'

df = pd.read_excel(filePath + parameters)

cusip_match = 'N'

#color columns U, Units & units.1 based on if there is a "N" Cell in column U.
colorMatch = df.style\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['U'])\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['Units'])\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['Units.1'])

#output File
colorMatch.to_excel(r"C:\\Users\\Desktop\\Match\\Large_Compare_Matches.xlsx")

executionTime = (time.time() - startTime)
print('Execution time in seconds: ' + str(executionTime))

I'm trying to color cells red within specified columns of a large XLSX file depending on if the Value in column U is "N".

I'm able to achieve this with my code below but it's taking over 20 minutes, would anyone have any suggestions on how I can improve performance to make this run faster?

import pandas as pd
import time

startTime = time.time()

filePath = r"C:\\Users\\Desktop\\Match\\"
parameters = 'large_file.xlsx'

df = pd.read_excel(filePath + parameters)

cusip_match = 'N'

#color columns U, Units & units.1 based on if there is a "N" Cell in column U.
colorMatch = df.style\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['U'])\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['Units'])\
    .apply(lambda x: ['background-color: red' if x == cusip_match else x for x in df.U],subset=['Units.1'])

#output File
colorMatch.to_excel(r"C:\\Users\\Desktop\\Match\\Large_Compare_Matches.xlsx")

executionTime = (time.time() - startTime)
print('Execution time in seconds: ' + str(executionTime))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女的英雄梦2025-01-21 06:12:42
DataFrame(df['U']).style.apply(lambda x: 'background-color: red' if x == cusip_match else x)
DataFrame(df['U']).style.apply(lambda x: 'background-color: red' if x == cusip_match else x)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文