【问题标题】:Creating pandas dataframes from nested json file that has lista从具有 lista 的嵌套 json 文件创建 pandas 数据帧
【发布时间】:2018-06-14 00:21:44
【问题描述】:

a picture on how the data look like

所以,我有一个带有数据的 json 文件,该文件确实是嵌套的,我只想获取单词并为每个帖子 ID 创建一个新的数据框。有人可以帮忙吗?

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    您可以将applylist comprehension 一起使用:

    df = pd.DataFrame({'member_info.vocabulary':[[], [{'post_iD':'3913', 'word':'Twisters'},
                                                      {'post_iD':'3911', 'word':'articulate'}]]})
    
    df['words'] = df['member_info.vocabulary'].apply(lambda x: [y.get('word') for y in x])
    print (df)
    
                                  member_info.vocabulary                   words
    0                                                 []                      []
    1  [{'post_iD': '3913', 'word': 'Twisters'}, {'po...  [Twisters, articulate]
    

    如果获取一个元素列表,只需添加 str[0] 以选择列表的第一个值:

    df = pd.DataFrame({'member_info.vocabulary':[[], [{'post_iD':'3913', 'word':'Twisters'}]]})
    
    df['words'] = df['member_info.vocabulary'].apply(lambda x: [y.get('word') for y in x]).str[0]
    print (df)
    
                          member_info.vocabulary     words
    0                                         []       NaN
    1  [{'post_iD': '3913', 'word': 'Twisters'}]  Twisters
    

    【讨论】:

    • 非常感谢您的快速回复:)。很有帮助。
    猜你喜欢
    • 2020-12-22
    • 2018-06-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2016-12-21
    • 2014-02-24
    相关资源
    最近更新 更多