将numpy.nd数组转换为json

时间:2017-04-11 12:44:57

标签: python arrays json numpy

我有一个数据框genre_rail,其中一列包含numpy.ndarray。数据框如下面datframe

所示

其中的数组如下所示:

['SINGTEL_movie_22906' 'SINGTEL_movie_22943' 'SINGTEL_movie_24404'
 'SINGTEL_movie_22924' 'SINGTEL_movie_22937' 'SINGTEL_movie_22900'
 'SINGTEL_movie_24416' 'SINGTEL_movie_24422']

我尝试使用以下代码

import json
json_content = json.dumps({'mydata': [genre_rail.iloc[i]['content_id'] for i in range(len(genre_rail))] })

但是出错了

  

TypeError:数组不是JSON可序列化的

我需要输出

{"Rail2_contend_id":
["SINGTEL_movie_22894","SINGTEL_movie_22898",
"SINGTEL_movie_22896","SINGTEL_movie_24609","SINGTEL_movie_2455",
"SINGTEL_movie_24550","SINGTEL_movie_24548","SINGTEL_movie_24546"]}

2 个答案:

答案 0 :(得分:13)

如何使用.tolist方法将数组转换为json。 然后你可以把它写成json,如:

np_array_to_list = np_array.tolist()
json_file = "file.json" 
json.dump(b, codecs.open(json_file, 'w', encoding='utf-8'), sort_keys=True, indent=4)

答案 1 :(得分:5)

将所有数据加载到字典中,然后将其转储到json。下面的代码可能对您有所帮助

import json

#Data
d = ['SINGTEL_movie_22906', 'SINGTEL_movie_22943', 'SINGTEL_movie_24404'
 'SINGTEL_movie_22924', 'SINGTEL_movie_22937', 'SINGTEL_movie_22900'
 'SINGTEL_movie_24416', 'SINGTEL_movie_24422']

#Create dict
dic = {}
dic['Rail2_contend_id'] = d

print dic

#Dump data dict to jason
j = json.dumps(dic)

输出

{' Rail2_contend_id':[' SINGTEL_movie_22906',' SINGTEL_movie_22943',' SINGTEL_movie_24404SINGTEL_movie_22924',' SINGTEL_movie_22937', ' SINGTEL_movie_22900SINGTEL_movie_24416',' SINGTEL_movie_24422']}