如果我有一个numpy dtype,我该如何自动将其转换为最接近的python数据类型?例如,
numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32 -> "python int"
numpy.int16 -> "python int"
Run Code Online (Sandbox Code Playgroud)
我可以尝试提出所有这些情况的映射,但是numpy是否提供了一些自动方式将其dtypes转换为最接近的可能的本机python类型?这种映射不一定是详尽无遗的,但它应该转换具有close python模拟的常见dtypes.我认为这已经发生在numpy的某个地方了.
背景:我正在编写一个应该管理我的音乐文件的python程序.它抓取目录并将以JSON编码的文件及其元数据(通过mutagen)作为简单的"数据库"放入文件中.我有很好的目录搜索,但是当我尝试保存数据库或编码为JSON时,它会抛出"TypeError:{...}不是JSON可序列化的"(...是来自dict的一些键和值,更多关于以下内容)
问题:程序按照以下格式构建一个大型字典对象:
{
"<song id>":{
"artist":"<song artist>",
"album":"<song album>",
"title":"<song title>"},
...
}
Run Code Online (Sandbox Code Playgroud)
每个歌曲文件都通过此格式编制索引.当我尝试将数据库转储到文件时,我得到了这个:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
sit()
File "D:\workbench\ideas\musicmanager\v0\spider.py", line 116, in sit
json.dump(js.db,f,True)
File "C:\Python27\lib\json\__init__.py", line 181, in dump
for chunk in iterable:
File "C:\Python27\lib\json\encoder.py", line 428, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "C:\Python27\lib\json\encoder.py", line 402, in _iterencode_dict
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 402, in _iterencode_dict
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 436, …Run Code Online (Sandbox Code Playgroud) 我有以下表格中的dicts列表,我从熊猫中生成.我想将其转换为json格式.
list_val = [{1.0: 685}, {2.0: 8}]
output = json.dumps(list_val)
Run Code Online (Sandbox Code Playgroud)
但是,json.dumps抛出一个错误:TypeError:685不是JSON可序列化的
我猜它是从numpy到python(?)的类型转换问题.
但是,当我使用np.int32(v)转换数组中每个dict的值v时,它仍会抛出错误.
编辑:这是完整的代码
new = df[df[label] == label_new]
ks_dict = json.loads(content)
ks_list = ks_dict['variables']
freq_counts = []
for ks_var in ks_list:
freq_var = dict()
freq_var["name"] = ks_var["name"]
ks_series = new[ks_var["name"]]
temp_df = ks_series.value_counts().to_dict()
freq_var["new"] = [{u: np.int32(v)} for (u, v) in temp_df.iteritems()]
freq_counts.append(freq_var)
out = json.dumps(freq_counts)
Run Code Online (Sandbox Code Playgroud)