如何使用Python编写excel文件,并向列的每一行添加一个后跟相同字符串的意图?

2024-06-28 18:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我有上面的代码来编写excel文件:

def write_excel(df):
    writer = pd.ExcelWriter("PATH\output.xlsx", engine = 'xlsxwriter')  

    workbook=writer.book
    worksheet=workbook.add_worksheet('sheet')
    writer.sheets['sheet'] = worksheet

    df.to_excel(writer, sheet_name='sheet', startcol = 0, startrow = 0)
    writer.save()

write_excel(df)

df是一个数据帧,看起来像:

ID             NUMBER      OBJECT
1345471886     SIZE-43     GHJ
1481654311     SIZE-48     IJF  
8620787660     SIZE-67     EFH

我在下面添加了这段代码,以向column对象添加缩进和字符串“hello you,hello”:

def add_agg_columns(df):
    df["OBJECT"] = df["OBJECT"] + "\n\nhello you, hello\n" 
    
    return df

我得到:

ID             NUMBER      OBJECT
1345471886     SIZE-43     GHJ\n\nhello you, hello\n
1481654311     SIZE-48     IJF\n\nhello you, hello\n  
8620787660     SIZE-67     EFH\n\nhello you, hello\n

在我的excel文件中,我希望我的最终输出如下所示:

ID             NUMBER      OBJECT
1345471886     SIZE-43     GHJ

                           hello you, hello
1481654311     SIZE-48     IJF
                        
                           hello you, hello
8620787660     SIZE-67     EFH

                           hello you, hello

但我现在写excel文件时得到的只是:

ID             NUMBER      OBJECT
1345471886     SIZE-43     GHJ
1481654311     SIZE-48     IJF  
8620787660     SIZE-67     EFH

Tags: 文件youidnumberhellodfsizeobject
1条回答
网友
1楼 · 发布于 2024-06-28 18:59:21

下面的代码实际上修复了它

last_sentence = """ 
hello you, hello
"""

def add_agg_columns(df):
    df["OBJECT"] = df["OBJECT"] + last_sentence 
    
    return df

def write_excel(df):
    writer = pd.ExcelWriter("PATH\output.xlsx", engine = 'xlsxwriter')  

    workbook=writer.book
    worksheet=workbook.add_worksheet('sheet')
    writer.sheets['sheet'] = worksheet

    df.to_excel(writer, sheet_name='sheet', startcol = 0, startrow = 0)
    writer.save()

write_excel(df)

相关问题 更多 >