在pandas多重索引数据框中添加空列导致重复项

1 投票
1 回答
34 浏览
提问于 2025-04-13 01:33

我正在尝试让两个数据表的结构一致。它们的列是一样的,除了其中一个数据表做过比较操作,所以它的列变成了多重索引,里面有“self”和“other”作为子列。

最后,我希望把这个调整好的数据表添加到那个做过比较操作的数据表里。

Existing df
                    Pants       Jacket
        Denim       yes         yes
        Cotton      no          no
        Silk        no          no


Goal structure
                    Pants           Jacket
                    self    other   self    other
        Denim       yes     new     yes     new
        Cotton      no      new     no      new
        Silk        no      new     no      new

我这样添加第一个子级,这样就把“self”这个元素加到了列里。

df_initial_unique.columns = [df_initial_unique.columns.get_level_values(0), np.repeat("self",df_initial_unique.shape[1])]

接下来,我想添加“other”这一列,所有元素的值都应该是“new”,我打算通过遍历列来实现。

for col in df_initial_unique.columns:
    df_initial_unique[(col,"other")] = "new"

但不知为什么,这样做并没有把“other”列作为子列添加进去,而是把所有列都复制了一遍,然后把“other”作为子列加上去。结果列的数量翻倍了。

                    Pants       Jacket      Pants       Jacket
                    self        self        other       other
        Denim       yes         yes         new         new
        Cotton      no          no          new         new
        Silk        no          no          new         new

我尝试了这里很多提出的解决方案,但似乎都没有效果。

1 个回答

1

一种可能的解决方案:

df.columns = pd.MultiIndex.from_product([df.columns, ["self"]])

df = df.reindex(
    pd.MultiIndex.from_product([df.columns.get_level_values(0), ["self", "other"]]),
    axis=1,
    fill_value="new",
)

print(df)

输出结果:

       Pants       Jacket      
        self other   self other
Denim    yes   new    yes   new
Cotton    no   new     no   new
Silk      no   new     no   new

撰写回答