首页 > 解决方案 > 将 JSON 文本字符串转换为 Pandas,但每个行单元格最终都作为内部值数组

问题描述

我设法从门户网站中提取时间序列的价格。数据以 json 格式到达,我将它们转换为 pandas 数据帧。

不幸的是,不同波段的数据来自一个文本字符串,我似乎无法正确提取它们。

下面是我提取的json数据

在此处输入图像描述

我使用此代码将它们转换为熊猫数据框

data = pd.DataFrame(r.json()['prices'])

让他们像这样

在此处输入图像描述

我需要提取(例如)ClosePrice 列中的数据,以便对它们进行数据分析和清理。

我尝试使用

data['closePrice'].str.split(',', expand=True).rename(columns = lambda x: "string"+str(x+1))

但它并没有真正起作用。

有没有办法a)当我将json转换为dataFrame时,以便在各个列中提取closePrice,bidPrice等中的价格或b)如果它们保存在dataFrame中,提取其中的文本字符串,例如我可以提取文本字符串中的价格(例如买价、卖价和lastTraded)吗?

标签: arraysjsonpython-3.xpandasjson-normalize

解决方案


import pandas as pd

data = r.json()

# print(data)

{'prices': [{'closePrice': {'ask': 1.16042, 'bid': 1.16027, 'lastTraded': None},
                        'highPrice': {'ask': 1.16052, 'bid': 1.16041, 'lastTraded': None},
                        'lastTradedVolume': 74,
                        'lowPrice': {'ask': 1.16038, 'bid': 1.16026, 'lastTraded': None},
                        'openPrice': {'ask': 1.16044, 'bid': 1.16038, 'lastTraded': None},
                        'snapshotTime': '2018/09/28 21:49:00',
                        'snapshotTimeUTC': '2018-09-28T20:49:00'}]}

df = pd.json_normalize(data['prices'])

输出:

|    |   lastTradedVolume | snapshotTime        | snapshotTimeUTC     |   closePrice.ask |   closePrice.bid | closePrice.lastTraded   |   highPrice.ask |   highPrice.bid | highPrice.lastTraded   |   lowPrice.ask |   lowPrice.bid | lowPrice.lastTraded   |   openPrice.ask |   openPrice.bid | openPrice.lastTraded   |
|---:|-------------------:|:--------------------|:--------------------|-----------------:|-----------------:|:------------------------|----------------:|----------------:|:-----------------------|---------------:|---------------:|:----------------------|----------------:|----------------:|:-----------------------|
|  0 |                 74 | 2018/09/28 21:49:00 | 2018-09-28T20:49:00 |          1.16042 |          1.16027 |                         |         1.16052 |         1.16041 |                        |        1.16038 |        1.16026 |                       |         1.16044 |         1.16038 |                        |

推荐阅读