Python从elasticsearch获取浮点作为浮点数组
在elasticsearch中,我的一个字段存储浮点值数组。比如说,Python从elasticsearch获取浮点作为浮点数组,python,arrays,
elasticsearch,Python,Arrays,
elasticsearch,在elasticsearch中,我的一个字段存储浮点值数组。比如说, -0.13672447204589844,0.18057402968406677,-0.099132493183133, 我试图检索这些值并将其存储在浮点数组中。我正在使用以下代码: res=es.search(index="g6jy834005er",body=data) arr=[] for hit in res['hits']['hits']: r="%(encod)s" % hit["_source"]
-0.13672447204589844,0.18057402968406677,-0.099132493183133,
我试图检索这些值并将其存储在浮点数组中。我正在使用以下代码:
res=es.search(index="g6jy834005er",body=data)
arr=[]
for hit in res['hits']['hits']:
r="%(encod)s" % hit["_source"]
print(r)
这将按如下方式打印阵列:
[[-0.11659730970859528, 0.019643619656562805, 0.08672580868005753]]
[[-0.11659730970859528, 0.019643619656562805, 0.08672580868005753]]
[[-0.11659730970859528, 0.019643619656562805, 0.08672580868005753]]
[[-0.11659730970859528, 0.019643619656562805, 0.08672580868005753]]
当我检查数组类型时,使用print(type(r))
我得到
<class 'str'>
<class 'str'>
<class 'str'>
他们都没有工作。如何将str数组转换为float数组 使用
ast.literal\u eval
:
import ast
res=es.search(index="g6jy834005er",body=data)
arr=[]
for hit in res['hits']['hits']:
r="%(encod)s" % hit["_source"]
r=ast.literal_eval(r)
print(r)
现在的类型与预期的一样,是一个列表
,但是如果您想要一个numpy数组:
import ast
res=es.search(index="g6jy834005er",body=data)
arr=[]
for hit in res['hits']['hits']:
r="%(encod)s" % hit["_source"]
r=np.array(ast.literal_eval(r))
print(r)
那么类型将是一个numpy数组。@u9forward谢谢您的快速回答……这两个选项都对我有帮助。到目前为止,我还没有见过ast图书馆。非常感谢。我会在7分钟内接受你的回答
import ast
res=es.search(index="g6jy834005er",body=data)
arr=[]
for hit in res['hits']['hits']:
r="%(encod)s" % hit["_source"]
r=np.array(ast.literal_eval(r))
print(r)