用换行符替换字符,以便输出CSV包含多行

时间:2019-06-26 17:23:41

标签: python pandas

我有一个带有一列的df,其中包含两个用分号“;”分隔的字符串。我已经用换行符“ \ n”替换了分号,然后使用带有text_wrap的xlsxwriter将文本包装在输出xlsx中;但是,我的输出与预期不符。

样品池的当前输出:

Monthly; Monthly

所需的输出(全部在同一单元内):

Monthly
Monthly

下面的代码部分将所有分号更改为换行符,然后使用text_wrap生成新格式并保存该工作簿。输出xlsx显示“每月每月”,没有换行符。我以为我的方法行不通。

    # Replace all semi-colons with newline characters
    df["col1"] = df["col1"].str.replace("; ", "\n") 
    df.to_excel("Spreadsheet.xlsx", index = False)

    writer = pd.ExcelWriter("Spreadsheet.xlsx", engine='xlsxwriter')
    df.to_excel(writer, sheet_name = "Sheet1", index = False)
    workbook = writer.book
    worksheet = writer.sheets["Sheet1"]
    workbook.add_format({"text_wrap" : True})
    worksheet.set_column("A:A", None, format)
    writer.save()

任何见识将不胜感激!谢谢。

0 个答案:

没有答案