arrays - 将 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)吗?
解决方案
- 用于
pandas.json_normalize
从dict
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 | |
推荐阅读
- c# - 进入和离开对象时如何制作弹出表单?C#
- ros - ROS Launcher 文件导致 roslaunch 出错
- c# - 执行 dotnet ef 迁移 remove 仅恢复模型快照
- python - 在 Plotly 中显示带有一条线的折线图的图表标签
- android - Google Drive Android - OAuth 同意屏幕显示错误的应用名称
- flutter - FlutterError(查找已停用小部件的祖先是不安全的)
- amazon-web-services - Terraform pathexpand 函数在复杂项目中不起作用?
- c++ - '-DLOCAL' 标志在 C++ 编译中的作用
- python - 使用 Python 删除大文件的每 5 个字节
- apache - 如何以非 root 用户身份运行 Apache?