【问题标题】:how to convert dictionary of list to pandas dataframe in python如何在python中将列表字典转换为熊猫数据框
【发布时间】:2021-02-16 17:09:14
【问题描述】:

我有这本包含项目列表的字典,但在将其转换为 pandas 数据框时遇到问题,这是我在到达端点时得到的响应

{'monologues': [{'speaker': 0,
   'elements': [{'type': 'text',
     'value': 'So',
     'ts': 0.0,
     'end_ts': 0.18,
     'confidence': 0.93},
    {'type': 'punct', 'value': ' '},
    {'type': 'text',
     'value': 'this',
     'ts': 0.18,
     'end_ts': 0.36,
     'confidence': 1.0},
    {'type': 'punct', 'value': ' '},
    {'type': 'text',
     'value': 'is',
     'ts': 0.36,
     'end_ts': 0.42,
     'confidence': 1.0},
    {'type': 'punct', 'value': '.'}]}]}

我想将 ts、end_ts 和 value 放入数据框

预期的数据框是:

    Words   ts      end_ts
0   so      0.0     0.18
1   this    0.18    0.36

这是我尝试过的,但没有给我预期的实际响应

import pandas as pd
df = pd.DataFrame(transcript_json, columns=transcript_json.keys())
df.head() 

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    您需要解析字典,然后将其附加到 DataFrame。

    import pandas as pd
    
    js = {'monologues': [{'speaker': 0,
       'elements': [{'type': 'text',
         'value': 'So',
         'ts': 0.0,
         'end_ts': 0.18,
         'confidence': 0.93},
        {'type': 'punct', 'value': ' '},
        {'type': 'text',
         'value': 'this',
         'ts': 0.18,
         'end_ts': 0.36,
         'confidence': 1.0},
        {'type': 'punct', 'value': ' '},
        {'type': 'text',
         'value': 'is',
         'ts': 0.36,
         'end_ts': 0.42,
         'confidence': 1.0},
        {'type': 'punct', 'value': '.'}]}]}
    
    inner_js = [val for _, val in js.items()][0][0]
    df = pd.DataFrame(columns=['Words', 'ts', 'end_ts'])
    for i in inner_js['elements']:
        if i.get('ts') or i.get('end_ts'):
            df = df.append({'Words':i['value'], 'ts':i['ts'], 'end_ts':i['end_ts']}, ignore_index=True)
    

    【讨论】:

    • 非常感谢,我很感激@DGS
    猜你喜欢
    • 2017-12-12
    • 2018-11-25
    • 1970-01-01
    • 2022-01-06
    • 2016-09-06
    • 2021-08-18
    • 2019-07-18
    • 1970-01-01
    • 2018-07-14
    相关资源
    最近更新 更多