簡體   English   中英

使用python在Excel中創建和保存數據新表

[英]Creating and saving data new sheet in excel using python

我是絕對的初學者,在下面的代碼中我使用了數據透視表,現在我想將數據透視表存儲在不同的工作表中(例如:“ Sheet 2”和“ sheet 3”)。 如何創建新工作表並將數據保存在其中。 是否可以將整個工作保存在令人興奮的工作表中(在我的情況下為“ Stratification_worksheet.xlxs”),並可以通過MS Excel進行檢查?

#importing pandas
import pandas as pd
import numpy as np
#Assigning the worksheet to file
file="Stratification_worksheet.xlsx"
#Loading the spreadsheet 
data= pd.ExcelFile(file)
#sheetname
print(data.sheet_names)
#loading the sheetname to df1
df=data.parse("Auftrag")
print(df)
# creating tuples
L1=["PMC11","PMP11","PMP21","PMC21","PMP23"]
L2=["PTP33B","PTP31B","PTC31B"]
m1=df["ordercode"].str.startswith(tuple(L1))
m2=df["ordercode"].str.startswith(tuple(L2))
#creating a new column preessurerange and slicing the pressure range from order code
a=df["ordercode"].str.slice(10,12)
b=df["ordercode"].str.slice(11,13)
df["pressurerange"]= np.select([m1,m2],[a,b], default =np.nan)
print(df)
#creating a new coloumn Presssureunit and slicing the preesure unit from ordercode
c=df["ordercode"].str.slice(12,13)
d=df["ordercode"].str.slice(14,15)
df["pressureunit"]= np.select([m1,m2],[c,d], default =np.nan)
print(df)  

#creating a tempcolumn to store pressurerange and pressure unit 
df["pressuresensor"]=df["pressurerange"] + df["pressureunit"]
print(df)

#pivottable 
print(df.pivot_table(values="total",columns="pressuresensor",aggfunc={"total":np.sum}))

print(df.pivot_table(values="total",columns="pressurerange",aggfunc={"total":np.sum}))

#check the columns
print(list(df))
print(df.dtypes)

如果您想寫而不丟失原始數據,請使用此

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\..."

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name = 'new')
df4.to_excel(writer, sheet_name = 'alsonew')
writer.save()
writer.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM