如何在 pandas 中执行“侧面视图explode()" [英] How to do 'lateral view explode()' in pandas

查看:83
本文介绍了如何在 pandas 中执行“侧面视图explode()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

# 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

每列A的值都是一个列表

Every column A's value is a list

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)

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

The above code can work but it's very slow

有什么聪明的方法吗?

谢谢

推荐答案

方法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)

方法2(pir)

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)

方法3(pir)

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)

感谢@ user113531参考亚历山大的答案.我必须对其进行修改才能正常工作.

Thanks @user113531 for the reference to Alexander's answer. I had to modify it to work.

(如果有帮助,请点击链接并进行投票)

(Follow link and Up Vote if this was helpful)

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

pd.DataFrame(rows, columns=df.columns)


时间

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


Timings

Method 4 (Alexander's) is the best followed by Method 3

这篇关于如何在 pandas 中执行“侧面视图explode()"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆