数据帧中的KeyError是否导致不正确的分组应用程序?

时间:2019-10-23 15:44:03

标签: python-3.x pandas dataframe indexing pandas-groupby

我使用.groupby.agg从另一个数据帧中提取了一个汇总数据帧。

sum_df = cnms_df.groupby(['Tiermetric', 'Mod_unMod', 'Val_Combined', 'Det_Approx', 'State', 'Region', 'CO_FIPS']).agg({'MILES': 'sum'})

但是,看起来有些不对劲;似乎缺少值。

Tiermetric Mod_unMod Val_Combined Det_Approx State Region CO_FIPS MILES 
Other 1    UnMapped  ASSESSED     Approx     IN    5      18001   8.397255
                                                          18003   3.284817
                                                          18011   64.019156
                                                          18017   9.068318
TIER 4     Modernized VALID       Detailed   NC    4      37119   2.046716
                                             NC    4      37120   59.890107
                                             NC    4      37025   3.773599

当我尝试做这样的事情时:

sum_df['CO_FIPS'][0]

我收到与索引相关的错误:

  

KeyError:'CO_FIPS'

我想要的是最终数据框如下所示:

Tiermetric Mod_unMod Val_Combined Det_Approx State Region CO_FIPS MILES 
Other 1    UnMapped  ASSESSED     Approx     IN    5      18001   8.397255
Other 1    UnMapped  ASSESSED     Approx     IN    5      18003   3.284817                    
Other 1    UnMapped  ASSESSED     Approx     IN    5      18011   64.019156
Other 1    UnMapped  ASSESSED     Approx     IN    5      18017   9.068318
TIER 4     Modernized VALID       Detailed   NC    4      37119   2.046716
TIER 4     Modernized VALID       Detailed   NC    4      37120   59.890107
TIER 4     Modernized VALID       Detailed   NC    4      37025   3.773599

我该如何解决?

2 个答案:

答案 0 :(得分:1)

groupby和sum导致所有这些列成为多索引。您可以使用0或传入reset_index()将索引变成列。

as_index=False

这同样适用于多索引。

答案 1 :(得分:0)

as_index设置为False,默认情况下为True

sum_df = cnms_df.groupby(as_index=False,by=['Tiermetric', 'Mod_unMod', 'Val_Combined', 'Det_Approx', 'State', 'Region', 'CO_FIPS']).agg({'MILES': 'sum'})