如何解决 pandas multi-column 爆炸问题?

how to solve pandas multi-column explode issue?

我正在尝试系统地一次爆炸multi-columns。 这样:

[

我希望最终输出为:

我试过了

df=df.explode('sauce', 'meal')

但这只提供了本例中第一个元素(sauce)被爆破,第二个没有被爆破。

我也试过:

df=df.explode(['sauce', 'meal'])

但此代码提供

ValueError: column must be a scalar

错误。

我试过了, and also this。 none 成功了。

注意:不能应用于索引,fruits 列中有一些 none- 唯一值。

在 pandas 1.3.0 之前使用:

df.set_index(['fruits', 'veggies'])[['sauce', 'meal']].apply(pd.Series.explode).reset_index()

输出:

  fruits veggies sauce meal
0     x1      y2     a    d
1     x1      y2     b    e
2     x1      y2     c    f
3     x2      y2     g    k
4     x2      y2     h    l

很多列?尝试:

df.set_index(df.columns.difference(['sauce', 'meal']).tolist())\
  .apply(pd.Series.explode).reset_index()

输出:

  fruits veggies sauce meal
0     x1      y2     a    d
1     x1      y2     b    e
2     x1      y2     c    f
3     x2      y2     g    k
4     x2      y2     h    l

更新您的 Pandas

版本
# Setup
df = pd.DataFrame({'fruits': ['x1', 'x2'],
                   'veggies': ['y1', 'y2'],
                   'sauce': [list('abc'), list('gh')],
                   'meal': [list('def'), list('kl')]})
print(df)

# Output
  fruits veggies      sauce       meal
0     x1      y1  [a, b, c]  [d, e, f]
1     x2      y2     [g, h]     [k, l]

爆炸 (Pandas 1.3.5):

out = df.explode(['sauce', 'meal'])
print(out)

# Output
  fruits veggies sauce meal
0     x1      y1     a    d
0     x1      y1     b    e
0     x1      y1     c    f
1     x2      y2     g    k
1     x2      y2     h    l