在 pandas df 中添加一个空列,其多索引与现有列相邻会创建重复项

问题描述 投票:0回答:1

我正在尝试协调两个数据帧的结构。 它们具有相同的列,除了其中一个已对其执行 df.compare() 的数据帧,因此它是一个以“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])]

然后我想添加“其他”列,它应该通过迭代列来为所有元素“新”具有相同的值。

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

由于某种原因,这不会将“其他”列添加为子列,而是复制所有列并将“其他”添加为子列。列的价值翻倍。

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

我尝试了这里提供的许多解决方案,但似乎都不起作用。

python pandas dataframe multi-index
1个回答
0
投票

一种可能的解决方案:

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
© www.soinside.com 2019 - 2024. All rights reserved.