【问题标题】:All possible combinations of two columns in a DataFrame while keeping the rest of the columns the sameDataFrame 中两列的所有可能组合,同时保持其余列相同
【发布时间】:2019-02-12 22:28:38
【问题描述】:

我有一个 Pandas 数据框,例如:

  Column_1   Column_2   Column_3   Column_4
0.   a          d          d1         d2
1.   b          e          e1         e2

并且我需要对 Column_1 和 Column_2 进行所有可能的组合,以使 Column_3 和 Column_4 的值与包含 Column_2 的行保持相同。这应该是输出:

  Column_1   Column_2   Column_3   Column_4
0.   a          d          d1         d2
1.   a          e          e1         e2
2.   b          d          d1         d2
3.   b          e          e1         e2

有人可以帮我解决这个问题吗?

【问题讨论】:

  • Column_1 实际上与数据框相关吗?看来您真正需要的是第 1 列(可能是一个单独的系列)与 DF 中的所有条目(即第 2-4 列)相结合,我理解正确吗?

标签: python pandas dataframe combinations


【解决方案1】:

我认为您正在寻找具有来自产品的多个索引的 reindex

col=df.columns
df.set_index(['Column_1','Column_2'],inplace=True)
idx=pd.MultiIndex.from_product([df.index.get_level_values(0),df.index.get_level_values(1)])
df=df.reindex(idx,method = 'ffill').reset_index()
df.columns=col
df

  Column_1 Column_2 Column_3 Column_4
0        a        d       d1       d2
1        a        e       d1       d2
2        b        d       d1       d2
3        b        e       e1       e2

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 2022-10-18
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多