python - 如何用 Python 编写一个 excel 文件并向列的每一行添加一个意图,然后是相同的字符串?
问题描述
嗨,我有上面的代码来编写一个 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
我在下面添加了这段代码,以在 OBJECT 列中添加缩进和字符串“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
解决方案
下面的代码实际上修复了它!
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)
推荐阅读
- java - 等待 Firestore 查询完成
- r - html 文件在 R 中显示问号而不是希伯来字符
- javascript - 我的阶乘函数逻辑有什么问题?
- android-studio-3.0 - 如何在每个按钮列表中编写 3 个不同的文本
- jersey - 如何使用嵌入式码头设置上下文路径?
- python - 使用 Matplotlib 在 python 中绘制多条曲线图
- python - 将 ldap 结果格式化为 json
- javascript - 是否可以以编程方式将一组姓名、电子邮件和主题行导出到 Google 表单“发送”功能?
- c# - 如何将一些列表发送到另一个班级以及如何连接它
- javascript - 将额外的 vs 一个参数传递给函数