先进的Python pandas 重塑 [英] Advanced Python pandas reshape
本文介绍了先进的Python pandas 重塑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为这类似于该帖子,但不完全相同,我无法理解.
I think this is similar to this post but not exactly the same and I cannot get my head around it.
所以,我目前有一个(很奇怪的)熊猫数据框,每个单元格中都有这样的列表:
So, I currently have a (quite weird) pandas dataframe with lists in each cell like this:
>>> data = pd.DataFrame({'myid' : ['1', '2', '3'],
'num' : [['1', '2', '3'], ['1', '2'], []],
'text' : [['aa', 'bb', 'cc'], ['cc', 'dd'],
[]]}).set_index('myid')
>>> print(data)
num text
myid
1 [1, 2, 3] [aa, bb, cc]
2 [1, 2] [cc, dd]
3 [] []
我想实现这一目标:
myid num text
0 1 1 aa
0 1 2 bb
0 1 3 cc
1 2 1 cc
1 2 2 dd
2 3
我怎么到达那里?
推荐答案
我将使用str.len
确定嵌入列表/数组的长度.然后使用repeat
和concatenate
I'd use str.len
to determine lengths of imbedded lists/arrays. Then use repeat
and concatenate
lens = df.num.str.len()
pd.DataFrame(dict(
myid=df.myid.repeat(lens),
num=np.concatenate(df.num),
text=np.concatenate(df.text)
)).append(
pd.DataFrame(
df.loc[~df.num.astype(bool), 'myid']
)
).fillna('')
myid num text
0 1 1 aa
0 1 2 bb
0 1 3 cc
1 2 1 cc
1 2 2 dd
2 3
这篇关于先进的Python pandas 重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文