我正在尝试过滤旋转数据框。但它在枢轴部分给出了错误。 我该如何解决这个问题?
可执行代码如下:
import numpy as np
df = pd.DataFrame({
'Year':[2022,2022,2023,2023,2024,2024],
'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
'Unit Price':[np.nan,200,None,56,75,65],
'Quantity':[1500, 140000, 1400000, 455, 648, 759],
'Amount':[100, 10000, 100000, 5, 48, 59],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
'energy':[100.,100,100,54,98,3],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount','Quantity']
columns_to_use = ['Year','Month']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
df3 = df2[df2['Category']=='alpha']
writer= pd.ExcelWriter(
"t2test2.xlsx",
engine='xlsxwriter'
)
df.to_excel(writer,sheet_name="t2",index=True)
df2.to_excel(writer,sheet_name="t2test",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)
writer.close()
import pandas as pd
import numpy as np
# Initialize DataFrame
df = pd.DataFrame({
'Year': [2022, 2022, 2023, 2023, 2024, 2024],
'Month': [1, 12, 11, 12, 1, 1],
'Code': [None, 'John Johnson', np.nan, 'John Smith', 'Mary Williams', 'Ted Bundy'],
'Unit Price': [np.nan, 200, None, 56, 75, 65],
'Quantity': [1500, 140000, 1400000, 455, 648, 759],
'Amount': [100, 10000, 100000, 5, 48, 59],
'Invoice': ['soccer', 'basketball', 'baseball', 'football', 'baseball', 'ice hockey'],
'Energy': [100., 100, 100, 54, 98, 3],
'Category': ['alpha', 'bravo', 'kappa', 'alpha', 'bravo', 'bravo']
})
# Set up pivot table
df2 = df.pivot_table(
index=['Category', 'Code', 'Invoice', 'Unit Price'],
values=['Amount', 'Quantity'],
columns=['Year', 'Month'],
aggfunc=np.sum, # Define an aggregation function, e.g., np.sum
fill_value=0 # Fill missing values with 0
)
# Filter the pivot table: using the index
df3 = df2.xs('alpha', level='Category')
# Excel output
writer = pd.ExcelWriter("t2test2.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name="t2", index=True)
df2.to_excel(writer, sheet_name="t2test", index=True)
df3.to_excel(writer, sheet_name="t2filter", index=True)
writer.close()
只需使用索引:
df2.loc[['alpha']]