我正在try 过滤旋转的螺旋桨.但它在支点部分出现了错误. 我该如何解决这个问题?

可执行代码如下:

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

推荐答案

由于您有索引级别(而不是列),因此只需使用带有loc的索引即可:

df3 = df2.loc[['alpha']]

输出:

                                        Amount           Quantity            
Year                                      2022 2023 2024     2022   2023 2024
Month                                       12   12   1        12     12   1 
Category Code       Invoice  Unit Price                                      
alpha    John Smith football 56.0          NaN  5.0  NaN      NaN  455.0  NaN

如果您想删除该级别:

df3 = df2.loc['alpha']

或者用xs:

df3 = df2.xs('alpha', level='Category')

输出:

                               Amount           Quantity            
Year                             2022 2023 2024     2022   2023 2024
Month                              12   12   1        12     12   1 
Code       Invoice  Unit Price                                      
John Smith football 56.0          NaN  5.0  NaN      NaN  455.0  NaN

Python相关问答推荐

如何从同一类的多个元素中抓取数据?

手动为pandas中的列上色

为什么我的主页不会重定向到详细视图(Django)

按日期和组增量计算总价值

如何在telegram 机器人中发送音频?

使用Python Cerberus初始化一个循环数据 struct (例如树)(v1.3.5)

有什么方法可以避免使用许多if陈述

Python plt.text中重叠,包adjust_text不起作用,如何修复?

如何计算列表列行之间的公共元素

使用plotnine和Python构建地块

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

try 与gemini-pro进行多轮聊天时出错

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

如何检测背景有噪的图像中的正方形

在Python中处理大量CSV文件中的数据

如何让程序打印新段落上的每一行?

当独立的网络调用不应该互相阻塞时,'

使用Python更新字典中的值

不能使用Gekko方程'

Python列表不会在条件while循环中正确随机化'