简体   繁体   English

JSON 到 Pandas dataframe 转换

[英]JSON to Pandas dataframe conversion

I have trouble with conversion of JSON formatted data to Pandas dataframe.我在将 JSON 格式的数据转换为 Pandas dataframe 时遇到问题。 My JSON data looks like this and is stored in the variable active_assets -我的 JSON 数据看起来像这样并存储在变量 active_assets 中 -

Asset({   'class': 'us_equity',
    'easy_to_borrow': True,
    'exchange': 'NYSE',
    'id': '879ac630-107f-43ce-a01d-1fd9da89453c',
    'marginable': True,
    'name': 'Zymeworks Inc.',
    'shortable': True,
    'status': 'active',
    'symbol': 'ZYME',
    'tradable': True}), Asset({   'class': 'us_equity',
    'easy_to_borrow': False,
    'exchange': 'NASDAQ',
    'id': 'a838c0cf-0008-432e-8882-feee5a6ef7cd',
    'marginable': True,
    'name': 'Zynerba Pharmaceuticals, Inc. Common Stock',
    'shortable': False,
    'status': 'active',
    'symbol': 'ZYNE',
    'tradable': True}), Asset({   'class': 'us_equity',
    'easy_to_borrow': True,
    'exchange': 'NASDAQ',
    'id': '52eed246-61b0-4e82-95a9-1d23906b752e',
    'marginable': True,
    'name': 'Zynex, Inc. Common Stock',
    'shortable': True,
    'status': 'active',
    'symbol': 'ZYXI',
    'tradable': True})

active_assets = api.list_assets(status='active',asset_class='us_equity')
df_dict = [{'SYMBL':i['symbol'], 'NAME':i['name'],'Shortable':i['shortable']} for i in active_assets['Asset']]
extracted_df = pd.DataFrame(df_dict)

When i run this code I get the following error?当我运行此代码时,出现以下错误? Any help is appreciated.任何帮助表示赞赏。

  File "D:\Trading-Scripts\Scan-alpaca.py", line 32, in <module>
    df_dict = [{'SYMBL':i['symbol'], 'NAME':i['name'],'Shortable':i['shortable']} for i in active_assets['Asset']]

TypeError: list indices must be integers or slices, not str

You are iterating over a dictionary in your dictionary comprehension.您正在对字典理解中的字典进行迭代。 Try to have i equal to your json object.尝试让 i 等于您的 json object。

You can also try to use the read_json method from pandas.您也可以尝试使用 pandas 中的 read_json 方法。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html

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

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