gpt4 book ai didi

python - Pandas to_excel 不写换行符

转载 作者:行者123 更新时间:2023-12-04 22:24:28 47 4
gpt4 key购买 nike

我正在尝试读取 Excel 并将数据写入带有新列的新 Excel。

这是一个示例 Excel module : 请忽略表格格式

+-------+------+------+
| Col1 | Col2 | Col3 |
+-------+------+------+
| Prod1 | "ABC | 100 |
XYZ"
| Prod2 | Test | 200 |
+-------+------+------+

我阅读了这个 excel 并通过以下方式在数据框中添加了一个新列:
df = pd.read_excel(module)
df["Status"] = ""

我通过以下方式在新列中添加一个值:
rowIndex = df.index[df['Col1'] == 'Prod1'].tolist()
df.loc[rowIndex, 'Status'] = 'Yes'

我写这个 df在一个新的excel中:
df.to_excel("output.xlsx", index = None, header=True)

但在新的 excel 数据中看起来像:
+-------+----------+------+-------+
| Col1 | Col2 | Col3 | Status|
+-------+----------+------+-------+
| Prod1 | "ABCXYZ" | 100 | Yes |

| Prod2 | Test | 200 | |
+-------+----------+------+-------+

如您所见, "ABCXYZ"排成一行。我希望它像在旧的 excel 中一样位于多行中。在新的 Excel 中写入数据时,我可以对代码进行哪些更改以保留这种格式?

P.S:调试时我发现 df值为 "ABC\nXYZ"但它仍然写在一行中。

最佳答案

我在下面找到了帮助我实现格式化的 python 库:

from StyleFrame import StyleFrame, Styler, utils

StyleFrame(df, styler_obj=Styler(horizontal_alignment=utils.horizontal_alignments.left, font = utils.fonts.calibri)).to_excel("output4.xlsx", index = None, header=True).save()

关于python - Pandas to_excel 不写换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59264311/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com