我正在尝试使用熊猫在excel中制定时间表。我目前将一天中的时间作为15分钟时间范围内的索引,并在每个单元格中打印占用这些类的类。我希望能够将具有重复类的所有行合并到一个大单元格中,但对于如何执行操作却一无所获。
时间表如何显示为熊猫数据框: pandas dataframe
时间表如何在Excel中打印: current excel schedule
我希望日程安排在excel中如何显示: dream excel schedule
有没有办法做到这一点?
答案 0 :(得分:1)
我肯定有更好的方法,但这是我想出的:
# create excel workbook from Pandas DataFrame
df.to_excel('output.xlsx', engine='xlsxwriter')
wb = load_workbook(filename='output.xlsx')
ws = wb.active
value = ''
same_values = [] # list to hold values that are the same
count = 0
for row in ws.iter_cols(): # iterate over each column
for cell in row: # iterate over each row in column
if count == 0: # this if block only get's used once in the beginning
value = cell.value
count += 1
same_values.append(cell.coordinate)
else:
if cell.value == ws[same_values[0]].value: # check if cell value is the same as what is in the same_value list
if cell.value is None: # if the cell.value is none skip
continue
same_values.append(cell.coordinate) # if the cell value is the same as what is in the same_value list then append the cell coordinate
else: # if the cell value is different than what is in the same_value list then merge everything in the same_value list
if len(same_values) > 1:
print(same_values)
ws.merge_cells(f'{same_values[0]}:{same_values[-1]}') # the same_value list only stores coordinates i.e ['B2', 'B3', 'B4'] so the merge_cells function takes a range of cells. So we are passing the coordinates of the first instance which is the first value (same_values[0]) of the same_value list and the last instance which is the last value (same_values[-1]) of the same_value list.
same_values = [cell.coordinate]
value = cell.value
wb.save('merged_output.xlsx')
答案 1 :(得分:0)
也许您正在使用xlsxwriter将Pandas数据框转换为excel文件?
看起来与这篇文章非常相似: Merge rows based on value (pandas to excel - xlsxwriter)