首页 > 解决方案 > Pandas,按最大返回 AssertionError 分组:

问题描述

熊猫有问题,我想听听你的意见,

我有这个数据框,我需要在其中获取最大值,代码就在下面,

df_stack=pd.DataFrame([[1.0, 2016.0, 'NonResidential', 'Hotel', 98101.0, 'DOWNTOWN',
        47.6122, -122.33799, 1927.0, 57.85220900338872,
        59.91269863912585],
       [1.0, 2016.0, 'NonResidential', 'Hotel', 98101.0, 'DOWNTOWN',
        47.61317, -122.33393, 1996.0, 55.82342114189166,
        56.86951201265458],
       [3.0, 2016.0, 'NonResidential', 'Hotel', 98101.0, 'DOWNTOWN',
        47.61393, -122.3381, 1969.0, 76.68191235628086,
        77.37931271575705],
       [5.0, 2016.0, 'NonResidential', 'Hotel', 98101.0, 'DOWNTOWN',
        47.61412, -122.33664, 1926.0, 68.53505428597694,
        71.00764283155655],
       [8.0, 2016.0, 'NonResidential', 'Hotel', 98121.0, 'DOWNTOWN',
        47.61375, -122.34047, 1980.0, 67.01346098859122,
        68.34485815906346]], columns=['OSEBuildingID', 'DataYear', 'BuildingType', 'PrimaryPropertyType', 
 'ZipCode', 'Neighborhood', 'Latitude', 'Longitude', 'YearBuilt', 
 'SourceEUI(KWm2)', 'SourceEUIWN(KWm2)' ])

当我运行下面的代码时:

df_stack[['OSEBuildingID', 
          'DataYear', 
          'BuildingType', 
          'PrimaryPropertyType', 
          'ZipCode', 'Neighborhood', 'Latitude', 'Longitude', 
          'YearBuilt', 'SourceEUI(KWm2)', 'SourceEUIWN(KWm2)']].groupby('OSEBuildingID').max()

我收到一个错误“AssertionError:”,如果您尝试这个,您可能会遇到同样的错误。但是,当我评论这两列并再次运行代码时

df_stack[['OSEBuildingID', 
          'DataYear', 
          #'BuildingType', 
          #'PrimaryPropertyType', 
          'ZipCode', 'Neighborhood', 'Latitude', 'Longitude', 
          'YearBuilt', 'SourceEUI(KWm2)', 'SourceEUIWN(KWm2)']].groupby('OSEBuildingID').max()

我得到结果

     DataYear  ZipCode Neighborhood  Latitude  Longitude  YearBuilt  SourceEUI(KWm2)  SourceEUIWN(KWm2)
OSEBuildingID                                                                                                    
1.0              2016.0  98101.0     DOWNTOWN  47.61317 -122.33393     1996.0        57.852209          59.912699
3.0              2016.0  98101.0     DOWNTOWN  47.61393 -122.33810     1969.0        76.681912          77.379313
5.0              2016.0  98101.0     DOWNTOWN  47.61412 -122.33664     1926.0        68.535054          71.007643
8.0              2016.0  98121.0     DOWNTOWN  47.61375 -122.34047     1980.0        67.013461          68.344858

如果我将 max() 替换为 mean(),我可以取消注释这两行并毫无问题地运行代码。这种行为只发生在 max() 和 min() 上,我只是测试 max、mean 和 min,但我需要得到最大值。

如果能帮上忙,谢谢。

标签: pythonpandas

解决方案


这是用修复的回归1.0.0'1.0.1',所以我建议你升级你的版本。

修复了 .groupby().agg() 中的回归,为一些减少(例如 object-dtype 列上的 min )引发 AssertionError (GH31522)


推荐阅读