如何在熊猫中进行'侧视爆炸()'

Zha*_*ong 11 python pandas

我想做这个 :

# input:
        A   B
0  [1, 2]  10
1  [5, 6] -20
# output:
   A   B
0  1  10
1  2  10
2  5 -20
3  6 -20
Run Code Online (Sandbox Code Playgroud)

每列A的值都是一个列表

df = pd.DataFrame({'A':[[1,2],[5,6]],'B':[10,-20]})
df = pd.DataFrame([[item]+list(df.loc[line,'B':]) for line in df.index for item in df.loc[line,'A']],
                  columns=df.columns)
Run Code Online (Sandbox Code Playgroud)

上面的代码可以工作,但速度很慢

有什么聪明的方法吗?

谢谢

piR*_*red 13

方法1(OP)

pd.DataFrame([[item]+list(df.loc[line,'B':]) for line in df.index for item in df.loc[line,'A']],
             columns=df.columns)
Run Code Online (Sandbox Code Playgroud)

方法2(皮尔)

df1 = df.A.apply(pd.Series).stack().rename('A')
df2 = df1.to_frame().reset_index(1, drop=True)
df2.join(df.B).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

方法3(皮尔)

A = np.asarray(df.A.values.tolist())
B = np.stack([df.B for _ in xrange(A.shape[1])]).T
P = np.stack([A, B])
pd.Panel(P, items=['A', 'B']).to_frame().reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

感谢@ user113531提供Alexander的回答.我不得不修改它才能工作.

方法4(@Alexander)链接答案

(如果有帮助,请关注链接和向上投票)

rows = []
for i, row in df.iterrows():
    for a in row.A:
        rows.append([a, row.B])

pd.DataFrame(rows, columns=df.columns)
Run Code Online (Sandbox Code Playgroud)

计时

方法4(亚历山大)是最好的方法3

在此输入图像描述