如何在 python 中反转多索引主元 table

How to reverse a multi index pivot table in python

我有一个数据框,我将其转换为数据透视表 table,对缺失数据执行一些插补,然后将其转换回原始形式。我的代码似乎可以工作,因为它不会产生错误,但输出不会产生预期的行数。我怀疑问题与指定 melting/stacking 有关,但不太清楚是什么。如果有人能够提供一些 help/support,我将不胜感激。图片、代码和更多信息如下。

提前感谢所有提供帮助的人。

初始数据框(数据)包含 4 列(geocode/country、变量名、年份和值)。共有 290,038 行 x 4 列。

我将 data 转换为以下形式(每一行中的国家/地区年份对,每一列都是一个变量)。使用以下代码

data_temp = data.copy()

data_temp_grouped = pd.pivot_table(data_temp, index=(['geocode','year']),columns="variablename",values="value")

执行一些 operations/imputation 后,我想将 data_temp_grouped 转换回原始形式 data。我尝试了几种不同的方法,代码没有产生预期的行数 (290,038)。

这会产生 4 列但 827,929 行。

data_temp_grouped2 = data_temp_grouped.copy()

data_temp_grouped3 = data_temp_grouped2.stack(0).reset_index(name='value')

这会产生 111,5712 行 x 4 列

data_temp_grouped2 = data_temp_grouped2.copy()

data_temp_grouped4 = data_temp_grouped4.reset_index()

data_temp_grouped4 = pd.melt(data_temp_grouped4,id_vars=["geocode","year"])

data_temp_grouped4

TLDR:我未能说明“添加”到长格式​​的宽格式“丢失”数据。

我刚刚意识到我为什么会遇到这些问题。在最初的长格式中,大约有 290,000 行。转换为宽格式时,有 7748(行)x144(列)。将其压缩为长格式后,共有 1,115,712 行 (7748 x 144)。这种增加是由于初始数据中不存在缺失数据(某些变量的国家/地区年份对)并且仅在转换为宽格式期间“出现”的事实。再次将其从长恢复到宽,尺寸匹配:如预期的 7748 x 144。

对于可能遇到同样问题的任何其他人,我还在下面包含了我的代码。 代码如下

# grouping country year pairs
data_temp = data.copy()
# converts into multi indexed wide format (country year pairs)
data_temp_grouped = pd.pivot_table(data_temp, index=(['geocode','year']),columns="variablename",values="value")

# linearly  interpolates the data for each country year pair
data_temp_grouped=data_temp_grouped.groupby("geocode").apply(lambda x : x.interpolate(method="linear",limit_direction="both"))

# Make a copy of the dataframe
data_temp_grouped2 = data_temp_grouped.copy()

# reset the index
data_temp_grouped2=data_temp_grouped2.reset_index()
data_temp_grouped2_melted=pd.melt(data_temp_grouped2,id_vars=['geocode',"year"],var_name='variablename', value_name='value')
data_temp_grouped2_melted

# to double check and convert back to multi index wide format
data_temp_grouped_check = pd.pivot_table(data_temp_grouped2_melted,index=(['geocode','year']),columns="variablename",values="value")