我有以下的框架:
2023-06-30 2022-06-30 2021-06-30 2020-06-30
Ordinary Shares Number 7432000000.0 7464000000.0 7519000000.0 7571000000.0
Share Issued 7432000000.0 7464000000.0 7519000000.0 7571000000.0
Net Debt 12533000000.0 35850000000.0 43922000000.0 49751000000.0
Total Debt 59965000000.0 61270000000.0 67775000000.0 70998000000.0
Tangible Book Value 128971000000.0 87720000000.0 84477000000.0 67915000000.0
... ... ... ... ...
Cash Cash Equivalents And Short Term Investments 111262000000.0 104757000000.0 130334000000.0 136527000000.0
Other Short Term Investments 76558000000.0 90826000000.0 116110000000.0 122951000000.0
Cash And Cash Equivalents 34704000000.0 13931000000.0 14224000000.0 13576000000.0
Cash Equivalents 26226000000.0 5673000000.0 6952000000.0 NaN
Cash Financial 8478000000.0 8258000000.0 7272000000.0 NaN
[73 rows x 4 columns]
字符串
我正在尝试将其转换为json,格式如下:
{
"2023-06-30": {
"Ordinary Shares Number": "7432000000.0",
...
},
"2022-06-30": {
"Ordinary Shares Number": "7464000000.0",
...
},
"2021-06-30": {
"Ordinary Shares Number": "7519000000.0",
...
},
"2020-06-30": {
"Ordinary Shares Number": "7571000000.0",
...
}
}
型
然而,我试图转换它已经从坏到更坏的范围,所以我真的不知道我在做什么。
我的尝试要么给了我一个非常不受欢迎的JSON格式,要么给了我一个关于时间戳的类型错误:
举例来说:
out = json.dumps({c: dict(zip(balance.index, balance[c])) for c in balance.columns}, indent=4)
print(out)
型
结果:
Traceback (most recent call last):
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/jesse_b/tools/stonk-db/stonkdb/__main__.py", line 39, in <module>
main()
File "/home/jesse_b/tools/stonk-db/stonkdb/__main__.py", line 32, in main
out = json.dumps({c: dict(zip(balance.index, balance[c])) for c in balance.columns}, indent=4)
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/usr/lib/python3.8/json/encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/usr/lib/python3.8/json/encoder.py", line 376, in _iterencode_dict
raise TypeError(f'keys must be str, int, float, bool or None, '
TypeError: keys must be str, int, float, bool or None, not Timestamp
型
2条答案
按热度按时间qpgpyjmq1#
你可以使用dict-comprehension:
字符串
印刷品:
型
zzwlnbp82#
我们可以通过将第一列设置为DataFrame的索引,然后使用
df.to_json(orient='columns')
将其转换为JSON来实现相同的JSON结构。在'columns'
方向上,JSON的形状是DataFrame中的每一列都成为一个键,对应的值存储在该键下的数组中。字符串
指纹
型