繁体   English   中英

如何在 python 中将列表字典转换为 pandas dataframe

[英]how to convert dictionary of list to pandas dataframe in python

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

{'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 放入 dataframe

预计 dataframe 是:

    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() 

您需要解析字典,然后将 append 解析为 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM