要嵌套到新列中的嵌套列表-Pandas,Python

问题描述 投票:0回答:1
data = {
    'user': ['Steeve', 'Pam', 'Olive'],
    'mentions': ['Pam', ['Steeve', 'Olive', 'Marc'], ['Paul', 'Lou']],
    'reply_to': [{'id': '123', 'username': 'alpha'}, [{'id': '231', 'username': 'beta'}, {'id': '4580', 'username': 'omega'}], {'id': '789', 'username': 'olo'}],
    'text': ['textfromSteeve', 'textfromPam', 'textfromOlive']
}

stack = pd.DataFrame(data, columns=['user','mentions','reply_to','text'])

[从这个数据帧中,我试图将mentionsreply_to列都转换为嵌套列表。然后的目标是应用熊猫爆炸功能为每个提及次数显示一行。例如,我想要3行用户“ Pam”,每行(Steeve,Olive和Marc)都提及一次。

到目前为止,我已经完成了以下操作:

def nested_list(li):
    temp = []
    for elem in li:
        temp.append([elem]) 
    return temp
stack['mentions_nested= stack.mentions.apply(lambda x: nested_list(x))
stack['replies_nested= stack.reply_to.apply(lambda x: nested_list(x))

问题是,当列中只有一个名称(字符串)时。它将每个字母分成一个单独的列表(例如:[[P],[a],[m]])。

关于reply_to列,字典的长度等于1,它返回类似以下的内容:[[id],[username]]。

你们对我该怎么做有任何想法吗?

仅供参考:在此同时,我将不会在两个提及reply_to列的地方都使用爆炸功能。这将是两个不同的过程。python

python pandas nested-lists data-processing
1个回答
0
投票

我相信您需要:

for c in ['mentions','reply_to']:
    stack[c] = stack[c].map(lambda x: x if isinstance(x, list) else [x])

print (stack)
     user               mentions  \
0  Steeve                  [Pam]   
1     Pam  [Steeve, Olive, Marc]   
2   Olive            [Paul, Lou]   

                                            reply_to            text  
0               [{'id': '123', 'username': 'alpha'}]  textfromSteeve  
1  [{'id': '231', 'username': 'beta'}, {'id': '45...     textfromPam  
2                 [{'id': '789', 'username': 'olo'}]   textfromOlive  
© www.soinside.com 2019 - 2024. All rights reserved.