Skip to main content
 首页 » 编程设计

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

2024年10月24日17wayfarer

我正在尝试写一个特定的 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 -- df 的 total 列:

df_total = df["total"] 

如果要保存DataFrame,df,那么

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

应该是

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