python - 根据值合并行( Pandas 到 excel - xlsxwriter)

标签 python excel pandas xlsxwriter

我正在尝试使用 xlsxwriter 将 Pandas 数据框输出到 excel 文件中。但是我正在尝试应用一些基于规则的格式;特别是尝试合并具有相同值的单元格,但在想出如何编写循环时遇到了麻烦。 (这里是 Python 新手!)

请参阅下面的输出与预期输出:

enter image description here

(正如您根据上图看到的那样,当它们具有相同的值时,我正在尝试合并“名称”列下的单元格)。

到目前为止,这是我所拥有的:

#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)

任何帮助是极大的赞赏!

谢谢!

最佳答案

您的逻辑几乎是正确的,但是我通过稍微不同的方法解决了您的问题:

1)对列进行排序,确保所有值都分组在一起。

2)重置索引(使用reset_index()并可能传递arg drop = True)。

3)然后我们必须捕获值是新的行。为此,创建一个列表并添加第一行 1,因为我们肯定会从那里开始。

4)然后开始迭代该列表的行并检查一些条件:

4a) 如果我们只有一行有值,merge_range 方法会报错,因为它不能合并一个单元格。在这种情况下,我们需要将 merge_range 替换为 write 方法。

4b) 使用此算法,您在尝试写入列表的最后一个值时会出现索引错误(因为它将它与下一个索引位置中的值进行比较,并且因为它是列表的最后一个值,所以没有下一个索引位置)。所以我们需要特别提到,如果我们得到一个索引错误(这意味着我们正在检查最后一个值),我们想要合并或写入直到数据帧的最后一行。

4c)最后我没有考虑该列是否包含空白或空单元格。在这种情况下,需要调整代码。

最后代码可能看起来有点困惑,你必须记住,pandas 的第一行索引为 0(标题是单独的),而 xlsxwriter 的标题索引为 0,第一行索引为 1。

这是一个工作示例,可以准确地实现您想要做的事情:

import pandas as pd

# Create a test df
df = pd.DataFrame({'Name': ['Tesla','Tesla','Toyota','Ford','Ford','Ford'],
                   'Type': ['Model X','Model Y','Corolla','Bronco','Fiesta','Mustang']})

# Create the list where we 'll capture the cells that appear for 1st time,
# add the 1st row and we start checking from 2nd row until end of df
startCells = [1]
for row in range(2,len(df)+1):
    if (df.loc[row-1,'Name'] != df.loc[row-2,'Name']):
        startCells.append(row)


writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
merge_format = workbook.add_format({'align': 'center', 'valign': 'vcenter', 'border': 2})


lastRow = len(df)

for row in startCells:
    try:
        endRow = startCells[startCells.index(row)+1]-1
        if row == endRow:
            worksheet.write(row, 0, df.loc[row-1,'Name'], merge_format)
        else:
            worksheet.merge_range(row, 0, endRow, 0, df.loc[row-1,'Name'], merge_format)
    except IndexError:
        if row == lastRow:
            worksheet.write(row, 0, df.loc[row-1,'Name'], merge_format)
        else:
            worksheet.merge_range(row, 0, lastRow, 0, df.loc[row-1,'Name'], merge_format)


writer.save()

输出:

enter image description here

关于python - 根据值合并行( Pandas 到 excel - xlsxwriter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61217923/

相关文章:

python - 通过使用字符串格式连接两个其他列来创建一个新列

python - -bash : ./manage.py:权限被拒绝

Excel VBA 代码竞争条件未通过等待、 sleep 、DoEvents 等修复

vba - 在VBA宏中使用日期变量?

python - 带有行号的 pandas 堆栈

python - 将包含年和周数的字符串转换为 Pandas 中的日期时间

python - timeit 如何受列表文字长度的影响?

Python 字符串不相等

python - 使用 SWIG 为 python2 和 python3 创建模块

excel - 在 Excel 中复制并重命名未打开的工作簿