使用熊猫将某个df写到下一个空列

时间:2022-03-03 15:51:03

I am trying to write a certain df which pertains total values calculated from two cells and then write a new column "total" with the values written on the next empty column.

我正在尝试编写一个特定的df,它包含从两个单元格计算出来的总值,然后用下一个空列上的值写一个新的列“total”。

Excel sheet consists of :

Excel表格包括:

Jan |Feb

10000   |62000

95000   |45000

91000   |120000

45000   |120000

162000  |120000

What I would like is:

我想要的是:

Jan |Feb  |Total

10000   |62000| 72000

95000   |45000|140000

91000   |120000 |211000

45000   |120000 | 165000

162000  |120000 | 282000

Instead of the totals column being written to the next column like I would like, it just overwrites the whole entire file with just the totals column being show. How would I go about writing my df_totals to the next empty column like I would like?

它不会像我希望的那样将总量列写到下一列,而是只显示总量列,覆盖整个文件。我要如何将df_total写到下一个空列中呢?

Code:

代码:

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()

contents inside xlsx after running the code:

运行代码后xlsx内部内容:

Total
72000
140000
211000
165000
282000

Thanks

谢谢

1 个解决方案

#1


1  

df_total is a Series -- the total column of df:

df_total是一个系列——df的总列:

df_total = df["total"]

If you want to save the DataFrame, df, then

如果您想保存DataFrame, df,则

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

should be

应该是

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

#1


1  

df_total is a Series -- the total column of df:

df_total是一个系列——df的总列:

df_total = df["total"]

If you want to save the DataFrame, df, then

如果您想保存DataFrame, df,则

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

should be

应该是

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