【发布时间】:2020-07-27 18:50:15
【问题描述】:
我正在尝试使用 xlsxwriter 将 Pandas 数据框输出到 excel 文件中。但是我正在尝试应用一些基于规则的格式;特别是试图合并具有相同值的单元格,但在想出如何编写循环时遇到了麻烦。 (这里是 Python 新手!)
输出与预期输出见下文:
(正如您根据上图看到的那样,当单元格具有相同的值时,我正在尝试合并“名称”列下的单元格)。
这是我目前所拥有的:
#This is the logic you use to merge cells in xlsxwriter (just an example)
worksheet.merge_range('A3:A4','value you want in merged cells', merge_format)
#Merge Car type Loop thought process...
#1.Loop through data frame where row n Name = row n -1 Name
#2.Get the length of the rows that have the same Name
#3.Based off the length run the merge_range function from xlsxwriter, worksheet.merge_range('range_found_from_loop','Name', merge_format)
for row_index in range(1,len(car_report)):
if car_report.loc[row_index, 'Name'] == car_report.loc[row_index-1, 'Name']
#find starting point based off index, then get range by adding number of rows to starting point. for example lets say rows 0-2 are similar I would get 'A0:A2' which I can then put in the code below
#from there apply worksheet.merge_range('A0:A2','[input value]', merge_format)
非常感谢任何帮助!
谢谢!
【问题讨论】:
-
你能澄清一下具体是什么问题吗?请提供minimal reproducible example。此外,除非绝对必要,否则请不要将信息作为图像共享。请参阅:meta.stackoverflow.com/questions/303812/…、idownvotedbecau.se/imageofcode、idownvotedbecau.se/imageofanexception。
-
@AMC 图像中没有代码。该图像是 excel 文件应该是什么样子的输出。代码在代码部分。
-
无论是代码还是数据,都适用相同的参数。
-
@AMC 让我知道它让您感到困惑的地方。问题是我不知道如何创建一个循环来查看前面的行,找到相似的值,并将合并函数应用于具有相同值的所有行;然后随后对整个数据帧执行此操作。 (请参阅图片,了解我正在尝试做的事情)。
-
您是否尝试过在纸上解决问题,编写伪代码之类的?
标签: python excel pandas xlsxwriter