Python-Pandas DataFrame中的巢状单元格 [英] Python - Unnest cells in Pandas DataFrame

查看:64
本文介绍了Python-Pandas DataFrame中的巢状单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有DataFrame df:

a b c
v f 3|4|5
v 2 6
v f 4|5

我想制作这个df:

a b c
v f 3
v f 4
v f 5
v 2 6
v f 4
v f 5

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

I know how to make this transformation in R, using tidyr package.

在大熊猫中有一种简单的方法吗?

Is there an easy way of doing this in pandas?

推荐答案

您可以:

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 ' '

获得:

   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

这篇关于Python-Pandas DataFrame中的巢状单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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