Python - Pandas DataFrame中的Unnest单元格

Gui*_*rte 8 python reshape dataframe pandas

假设我有DataFrame df:

a b c
v f 3|4|5
v 2 6
v f 4|5
Run Code Online (Sandbox Code Playgroud)

我想生产这个df:

a b c
v f 3
v f 4
v f 5
v 2 6
v f 4
v f 5
Run Code Online (Sandbox Code Playgroud)

我知道如何使用tidyr包在R中进行这种转换.

在熊猫中有这么简单的方法吗?

Ste*_*fan 2

你可以:

import numpy as np

df = df.set_index(['a', 'b'])
df = df.astype(str) + '| ' # There's a space ' ' to match the replace later
df = df.c.str.split('|', expand=True).stack().reset_index(-1, drop=True).replace(' ', np.nan).dropna().reset_index() # and replace also has a space ' '
Run Code Online (Sandbox Code Playgroud)

要得到:

   a  b  0
0  v  f  3
1  v  f  4
2  v  f  5
3  v  2  6
4  v  f  4
5  v  f  5
Run Code Online (Sandbox Code Playgroud)