我有一个数据集 ( df2 ),如下所示:
total_n
ind_n4 year city_code
9 2003 a 236
2004 a 520
54 2002 b 167
2004 b 997
2005 b 476
2006 b 742
数据集示例:
df = pd.DataFrame( {'year':[2003,2004,2002,2004,2005,2006],
'city_code':['a']*2+['b']*4,
'total_tax':pd.np.random.randint(100,1000,6)},
index=pd.Index(data=[9]*2+[54]*4,name='ind_n4'))
df1 = df.set_index('year',append=True)
df2 = df1.set_index('city_code',append=True)
我正在寻找的输出是一个余额表,如下所示:
total_n
ind_n4 city_code year
9 a 2002 0
2003 236
2004 520
2005 0
2006 0
b 2002 0
2003 0
2004 0
2005 0
2006 0
54 a 2002 0
2003 0
2004 0
2005 0
2006 0
b 2002 167
2003 0
2004 997
2005 476
2006 742
为此,我一直在使用这种方法,该方法是针对 Python Pandas: Balance an unbalanced dataset (for panel analysis) 中的一个相当相似的示例提出的建议。 :
df_balanced = (df.set_index('year',append=True)
.reindex(pd.MultiIndex.from_product([df.index.unique(),
range(df.year.min(),df.year.max()+1)],
names=['id_inf','year']))
.reset_index(level=1))
但是,当我使用此代码时,我收到一条错误消息:NotImplementedError: isna is not Define for MultiIndex
非常感谢您的帮助
最佳答案
使用这个:
df3 = df2.swaplevel(1,2)
df3.reindex(pd.MultiIndex.from_product(df3.index.levels), fill_value=0)\
.rename_axis(df3.index.names, axis=0)
输出:
total_tax
ind_n4 city_code year
9 a 2002 0
2003 317
2004 233
2005 0
2006 0
b 2002 0
2003 0
2004 0
2005 0
2006 0
54 a 2002 0
2003 0
2004 0
2005 0
2006 0
b 2002 956
2003 0
2004 609
2005 626
2006 811
详细信息:
- 如果需要,请使用交换级别以获得正确的索引级别 订单。
- 使用 pd.MultiIndex.from_product 的索引级别,您可以创建 所有组合均按该层次顺序排列。
- 使用 reindex 通过 fill_value 参数创建缺失的行。
- 最后,重命名索引级别。
关于Python:平衡回归分析的数据集(重新排列数据集并填充空白类别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53545709/