如何将以下json输出放入pandas数据帧?
[{'currency': '1ST', 'available': '0', 'reserved': '0'}, {'currency': '8BT', 'available': '0', 'reserved': '0'}, {'currency': 'ADX', 'available': '0', 'reserved': '0'}, {'currency': 'AE', 'available': '0', 'reserved': '0'}, {'currency': 'AEON', 'available': '0', 'reserved': '0'}, {'currency': 'AIR', 'available': '0', 'reserved': '0'}, {'currency': 'AMB', 'available': '0', 'reserved': '0'}, {'currency': 'AMM', 'available': '0', 'reserved': '0'}, {'currency': 'AMP', 'available': '0', 'reserved': '0'}]
我尝试过以下操作,但只收到以下错误:
代码
balances = pd.read_json(data)
错误
ValueError: Invalid file path or buffer object type: <class 'method'>
编辑 - 我如何获取数据:
def get_account_balance(self):
"""Get main balance."""
return self.session.get("https://api.hitbtc.com/api/2/account/balance").json()
答案 0 :(得分:2)
IIUC假设你有一本字典:
In [231]: d = [{'currency': 'ZRX', 'available': '0', 'reserved': '0'}, {'currency': 'ZSC', 'available': '0', 'reserved': '0'}]
In [235]: pd.DataFrame(d)
Out[235]:
available currency reserved
0 0 ZRX 0
1 0 ZSC 0
如果它是一个字符串(损坏的JSON,因为JSON必须有双引号而不是单引号):
import json
In [238]: s = """
...: [{'currency': 'ZRX', 'available': '0', 'reserved': '0'}, {'currency': 'ZSC', 'available': '0', 'reserved': '0'}]
...: """
In [239]: d = json.loads(s.replace("'", '"'))
In [240]: pd.DataFrame(d)
Out[240]:
available currency reserved
0 0 ZRX 0
1 0 ZSC 0
答案 1 :(得分:1)
将json文件导入到pandas数据框时遇到了同样的问题。我通过展平字典然后正常导入它们来解决了这个问题:
def get_values(lVals):
res = []
for val in lVals:
if type(val) not in [list, set, tuple]:
res.append(val)
else:
res.extend(get_values(val))
return res
data = get_values(data)
df = pd.DataFrame(data)
答案 2 :(得分:0)
以下对我有用:
pd.DataFrame.from_dict(data, orient='columns')
来源:https://github.com/vi3k6i5/pandas_basics/blob/master/1_a_create_a_dataframe_from_dictonary.ipynb
答案 3 :(得分:0)
参考:
Python how convert single quotes to double quotes to format as json string | user3850
import json
import pandas as pd
json_data = [{'currency': '1ST', 'available': '0', 'reserved': '0'}, {'currency': '8BT', 'available': '0', 'reserved': '0'}, {'currency': 'ADX', 'available': '0', 'reserved': '0'}, {'currency': 'AE', 'available': '0', 'reserved': '0'}, {'currency': 'AEON', 'available': '0', 'reserved': '0'}, {'currency': 'AIR', 'available': '0', 'reserved': '0'}, {'currency': 'AMB', 'available': '0', 'reserved': '0'}, {'currency': 'AMM', 'available': '0', 'reserved': '0'}, {'currency': 'AMP', 'available': '0', 'reserved': '0'}]
json_format = json.dumps(json_data)
json_df = pd.read_json(json_format)
json_df.head()