Python 在 numpy 数组的元素之间添加逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32026636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add a comma between the elements of a numpy array
提问by ulrich
I have a numpy array which looks like
我有一个 numpy 数组,它看起来像
a = ['blue' 'red' 'green']
and I want it to become
我希望它成为
b = ['blue', 'red', 'green']
I tried
我试过
b = a.split(' ')
but it returns an error: 'numpy.ndarray' object has no attribute 'split'
但它返回一个错误: 'numpy.ndarray' object has no attribute 'split'
采纳答案by DeepSpace
Simply turn it to a list:
只需将其转换为列表:
a = numpy.array(['blue', 'red', 'green'])
print a
>> ['blue' 'red' 'green']
b = list(a)
print b
>> ['blue', 'red', 'green']
But why would you have a numpy array with strings?
但是为什么你会有一个带字符串的 numpy 数组呢?
回答by Padraic Cunningham
You can simply call tolist:
您可以简单地调用 tolist:
import numpy as np
a = np.array(['blue', 'red', 'green'])
b = a.tolist()
print(b)
['blue', 'red', 'green']
回答by hebeha
I had a similar problem with a list without commas and with arbitrary number of spaces. E.g.:
我有一个没有逗号和任意数量空格的列表的类似问题。例如:
[2650 20 5]
[2670 5]
[1357 963 355]
I solved it this way:
我是这样解决的:
np.array(re.split("\s+", my_list.replace('[','').replace(']','')), dtype=int)
From the console:
从控制台:
>>> import numpy as np
>>> import re
>>> my_list = '[2650 20 5]'
>>> result = np.array(re.split("\s+", my_list.replace('[','').replace(']','')), dtype=int)
>>> result
array([2650, 20, 5])
>>>