我是绝对的初学者,在下面的代码中我使用了数据透视表,现在我想将数据透视表存储在不同的工作表中(例如:“工作表2”和“工作表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()