gpt4 book ai didi

python - 使用 Pandas 将某个 df 写入下一个空列

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:06 25 4
gpt4 key购买 nike

我正在尝试写一个特定的 df,它涉及从两个单元格计算的总值,然后写一个新列“总计”,其中的值写在下一个空列上。

Excel 工作表包括:

Jan |Feb

10000 |62000

95000 |45000

91000 |120000

45000 |120000

162000 |120000

我想要的是:

Jan |Feb  |Total

10000 |62000| 72000

95000 |45000|140000

91000 |120000 |211000

45000 |120000 | 165000

162000 |120000 | 282000

不像我希望的那样将总计列写入下一列,它只是覆盖整个文件,只显示总计列。我将如何像我希望的那样将我的 df_totals 写入下一个空列?

代码:

import pandas as pd
import numpy as np
from pandas import ExcelWriter

df = pd.read_excel("samplesheet.xlsx")
df["total"] = df["Jan"] + df["Feb"] + df["Mar"]
df.head()

df_total = df["total"]
print(df_total)
print("")


df_total = pd.DataFrame(df_total)
writer = ExcelWriter('samplesheet.xlsx')
df_total.to_excel(writer,'Sheet1',index=False)
writer.save()

运行代码后xlsx里面的内容:

Total
72000
140000
211000
165000
282000

谢谢

最佳答案

df_total 是一个 Series -- dftotal 列:

df_total = df["total"]

如果要保存DataFrame,df,那么

df_total.to_excel(writer,'Sheet1',index=False)

应该是

df.to_excel(writer,'Sheet1',index=False)

关于python - 使用 Pandas 将某个 df 写入下一个空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617067/

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