我使用.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
我该如何解决?
答案 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'})