【问题标题】:When using json_normalized, keep getting a json TypeError使用 json_normalized 时,不断收到 json TypeError
【发布时间】:2020-08-17 07:11:30
【问题描述】:

为什么我总是收到类型错误:字符串索引必须是整数

代码是:

import pandas as pd
from pandas.io.json import json_normalize

data = json.dumps(result, indent=4)
FIELDS = ["address", "balance"]
df_norm = json_normalize(data["accounts"])

print(df_norm[FIELDS])

JSON 结构如下:

{
    "accounts": [
        {
            "address": "0x000000000000000000000000000000000000dead",
            "balance": "64714244635198"
        },
        {
            "address": "0x00000000af5a61acaf76190794e3fdf1289288a1",
            "balance": "29416569893502257"
        }
]

我以这篇文章为指导:https://medium.com/swlh/converting-nested-json-structures-to-pandas-dataframes-e8106c59976e

【问题讨论】:

  • pd.DataFrame(data['accounts'])怎么样
  • 出现同样的错误TypeError: string indices must be integers
  • 那你的数据结构和描述的不一样

标签: json pandas


【解决方案1】:

您可以使用record_path 参数。我使用的是熊猫 1.1.0 版:

df = pd.json_normalize(data, record_path=['accounts'])
print(df)

                                      address            balance
0  0x000000000000000000000000000000000000dead     64714244635198
1  0x00000000af5a61acaf76190794e3fdf1289288a1  29416569893502257

【讨论】:

  • 我仍然收到TypeError: string indices must be integers
猜你喜欢
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
相关资源
最近更新 更多