Numpy将阵列数组转换为1D

时间:2015-06-20 05:36:35

标签: python arrays numpy reshape

如何让x成为一维数组? 我发现像这样创建x很方便,

x=np.array([[0,-1,0]*12,[-1,0,0]*4])
print x
print len(x)

返回

array([ [0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0],
       [-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0]], dtype=object)

2

我也试过这样做,但长度仍然是2

y=((0,1,0)*12,(-1,0,0)*4)
print y

返回

((0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0), (-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0))

我尝试过使用numpy.reshape(在x和y上):

np.reshape(x,48)

但是我收到了这个错误:

ValueError: total size of new array must be unchanged

当我像我一样宣布它时,是否有可能重塑x或y?

2 个答案:

答案 0 :(得分:2)

创建数组时,将列表与$url = "http://freegeoip.net/json/$ip"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $data = curl_exec($ch); curl_close($ch); 连接起来,而不是将它们打包在另一个列表中:

{
["ip"]=> string(11) "59.90.210.9" 
["country_code"]=> string(2) "IN" 
["country_name"]=> string(5) "India" 
["region_code"]=> string(0) "" 
["region_name"]=> string(0) "" 
["city"]=> string(0) "" 
["zip_code"]=> string(0) "" 
["time_zone"]=> string(12) "Asia/Kolkata" 
["latitude"]=> int(20) 
["longitude"]=> int(77) 
["metro_code"]=> int(0) 
} 

答案 1 :(得分:0)

我认为你正在寻找一个长度为48的1D numpy数组。试试,

    import numpy as np
    x=np.array([[0,-1,0]*12])
    x= np.append(x,[-1,0,0]*4)
    print (x)
    print (len(x))

这会产生,

[ 0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0
 -1  0  0 -1  0  0 -1  0  0 -1  0 -1  0  0 -1  0  0 -1  0  0 -1  0  0]
48