在python中向整数数组追加一些值
如何使用append或任何其他方法向该整数数组“a”添加值?出现错误的原因是无法将值追加到在python中向整数数组追加一些值,python,arrays,numpy,integer,Python,Arrays,Numpy,Integer,如何使用append或任何其他方法向该整数数组“a”添加值?出现错误的原因是无法将值追加到numpy.array。如果a是列表,您就不会有问题 看起来这就是你要找的: import numpy as np c=[4,8,2,3........] a=np.array([2,3,5],np.int16) #data type=np.int16=Integer(-32768 +32767)) for i in range(len(c)): a.append(c[i]) # This
numpy.array
。如果a
是列表
,您就不会有问题
看起来这就是你要找的:
import numpy as np
c=[4,8,2,3........]
a=np.array([2,3,5],np.int16) #data type=np.int16=Integer(-32768 +32767))
for i in range(len(c)):
a.append(c[i]) # This line getting error
如果a
和c
是numpy.array
,您可以:
In [4]: a = [2,3,5]
In [5]: c = [4,8,2,3]
In [6]: a.extend(c)
In [7]: a
Out[7]: [2, 3, 5, 4, 8, 2, 3]
出现错误的原因是无法附加到
numpy.array
。如果a
是列表
,您就不会有问题
看起来这就是你要找的:
import numpy as np
c=[4,8,2,3........]
a=np.array([2,3,5],np.int16) #data type=np.int16=Integer(-32768 +32767))
for i in range(len(c)):
a.append(c[i]) # This line getting error
如果a
和c
是numpy.array
,您可以:
In [4]: a = [2,3,5]
In [5]: c = [4,8,2,3]
In [6]: a.extend(c)
In [7]: a
Out[7]: [2, 3, 5, 4, 8, 2, 3]
好的,根据文档,numpy数组没有函数append 以下是对代码的更正:
In [12]: a = np.array([2,3,5])
In [13]: c = np.array([4,8,2,3])
In [14]: np.concatenate((a,c))
Out[14]: array([2, 3, 5, 4, 8, 2, 3])
我猜这就是你想要做的,根据文档,这是一个你可以使用的免费功能。我希望这对您有所帮助。好的,根据文档,numpy数组没有附加功能 以下是对代码的更正:
In [12]: a = np.array([2,3,5])
In [13]: c = np.array([4,8,2,3])
In [14]: np.concatenate((a,c))
Out[14]: array([2, 3, 5, 4, 8, 2, 3])
我猜这就是你想要做的,根据文档,这是一个你可以使用的免费功能。我希望这对您有所帮助。列表在逐项构建方面比numpy数组更高效。如果您想一个接一个地追加,我建议您将其追加到列表中,然后使用
np.array(myList)
将其转换为numpy数组。执行与代码相同的操作的更快方法是:
import numpy as np
c=[4,8,2,3........]
a=np.array([2,3,5],np.int16) #data type=np.int16=Integer(-32768 +32767))
for i in range(len(c)):
a = np.append(a, c[i]) # This line getting error
如果您只想将c
列表转换为int16
数组:
a = np.array(list(a) + c, np.int16)
然后,您可以按照@Akavall将其连接起来,或者使用更紧凑的np.r\ucode>形式(注意方括号)
列表在逐项构造方面比numpy数组更有效。如果您想一个接一个地追加
,我建议您将其追加到列表中,然后使用np.array(myList)
将其转换为numpy数组。执行与代码相同的操作的更快方法是:
import numpy as np
c=[4,8,2,3........]
a=np.array([2,3,5],np.int16) #data type=np.int16=Integer(-32768 +32767))
for i in range(len(c)):
a = np.append(a, c[i]) # This line getting error
如果您只想将c
列表转换为int16
数组:
a = np.array(list(a) + c, np.int16)
然后,您可以按照@Akavall将其连接起来,或者使用更紧凑的np.r\ucode>形式(注意方括号)
下面的一些代码比较了将2D Python小整数列表转换为1D Numpy数组的3种不同方法的速度
简单的方法是将整个列表传递给Numpy的array
函数,然后通过其.flatten
方法将生成的2D数组展平为1D。这是网格到数组所采用的方法
我测试的其他方法都使用numpy.append
函数grid\u rows\u to\u array
逐行构建数组,grid\u items\u to\u array
逐项构建数组。正如您可能猜到的,最后一种方法非常缓慢。即使是10x10列表,其速度也比网格到网格阵列慢50倍左右。对于更大的列表,它的速度确实很慢
a = np.r_[a,c]
输出
#!/usr/bin/env python3
''' Compare the speeds of various functions that convert a
2D integer list to a 1D Numpy array.
See https://stackoverflow.com/q/44512661/4014959
Written by PM 2Ring 2017.06.13
'''
import numpy as np
from timeit import Timer
def make_grid(n):
''' Make a 2D list of integers '''
return [list(range(i, i + n)) for i in range(0, n * n, n)]
# The functions to test
def grid_to_array(g):
''' Create a 2D array from the whole grid and convert it to 1D '''
return np.array(g).flatten()
def grid_rows_to_array(g):
''' Create a 1D array from the 1st row of the grid,
then append all the other rows to it, row by row
'''
# An iterator that yields the rows
it = iter(g)
a = np.array(next(it))
for row in it:
a = np.append(a, row)
return a
def grid_items_to_array(g):
''' Create an array from the 1st item of the grid,
then append all the other items to it, item by item
'''
# A generator that yields the items
gen = (u for row in g for u in row)
a = np.array(next(gen))
for u in gen:
a = np.append(a, u)
return a
funcs = (
grid_to_array,
grid_rows_to_array,
grid_items_to_array,
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def verify(size):
''' Verify that all the functions give the same result '''
print('Grid rows, size=', size)
grid = make_grid(size)
for row in grid:
print(row)
print()
results = []
for func in funcs:
print(func.__name__)
a = func(grid)
print(a, '\n')
results.append(a)
# Test that all arrays are identical
first, *results = results
rc = all((first == u).all() for u in results)
print('all ok' if rc else 'Error!')
return rc
def time_test(loops, reps):
''' Print timing stats for all the functions '''
timings = []
for func in funcs:
fname = func.__name__
setup = 'from __main__ import grid, ' + fname
cmd = fname + '(grid)'
t = Timer(cmd, setup)
result = t.repeat(reps, loops)
result.sort()
timings.append((result, fname))
timings.sort()
for result, fname in timings:
print('{:20} {}'.format(fname, result))
verify(5)
# Do the timing tests
reps = 3
loops = 128
for i in range(6):
size = 10 * (2 ** i)
grid = make_grid(size)
print('\n{0}: Size={1}, Loops={2}'.format(i, size, loops))
time_test(loops, reps)
loops >>= 1
这些计时是使用Python3.6.0在一台相当古老的2GHz单核32位机器上获得的,该机器具有2GB的RAM,运行Linux的Debian派生版本。YMMV.下面是一些代码,比较了将2D Python小整数列表转换为1D Numpy数组的3种不同方法的速度
简单的方法是将整个列表传递给Numpy的array
函数,然后通过其.flatten
方法将生成的2D数组展平为1D。这是网格到数组所采用的方法
我测试的其他方法都使用numpy.append
函数grid\u rows\u to\u array
逐行构建数组,grid\u items\u to\u array
逐项构建数组。正如您可能猜到的,最后一种方法非常缓慢。即使是10x10列表,其速度也比网格到网格阵列慢50倍左右。对于更大的列表,它的速度确实很慢
a = np.r_[a,c]
输出
#!/usr/bin/env python3
''' Compare the speeds of various functions that convert a
2D integer list to a 1D Numpy array.
See https://stackoverflow.com/q/44512661/4014959
Written by PM 2Ring 2017.06.13
'''
import numpy as np
from timeit import Timer
def make_grid(n):
''' Make a 2D list of integers '''
return [list(range(i, i + n)) for i in range(0, n * n, n)]
# The functions to test
def grid_to_array(g):
''' Create a 2D array from the whole grid and convert it to 1D '''
return np.array(g).flatten()
def grid_rows_to_array(g):
''' Create a 1D array from the 1st row of the grid,
then append all the other rows to it, row by row
'''
# An iterator that yields the rows
it = iter(g)
a = np.array(next(it))
for row in it:
a = np.append(a, row)
return a
def grid_items_to_array(g):
''' Create an array from the 1st item of the grid,
then append all the other items to it, item by item
'''
# A generator that yields the items
gen = (u for row in g for u in row)
a = np.array(next(gen))
for u in gen:
a = np.append(a, u)
return a
funcs = (
grid_to_array,
grid_rows_to_array,
grid_items_to_array,
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def verify(size):
''' Verify that all the functions give the same result '''
print('Grid rows, size=', size)
grid = make_grid(size)
for row in grid:
print(row)
print()
results = []
for func in funcs:
print(func.__name__)
a = func(grid)
print(a, '\n')
results.append(a)
# Test that all arrays are identical
first, *results = results
rc = all((first == u).all() for u in results)
print('all ok' if rc else 'Error!')
return rc
def time_test(loops, reps):
''' Print timing stats for all the functions '''
timings = []
for func in funcs:
fname = func.__name__
setup = 'from __main__ import grid, ' + fname
cmd = fname + '(grid)'
t = Timer(cmd, setup)
result = t.repeat(reps, loops)
result.sort()
timings.append((result, fname))
timings.sort()
for result, fname in timings:
print('{:20} {}'.format(fname, result))
verify(5)
# Do the timing tests
reps = 3
loops = 128
for i in range(6):
size = 10 * (2 ** i)
grid = make_grid(size)
print('\n{0}: Size={1}, Loops={2}'.format(i, size, loops))
time_test(loops, reps)
loops >>= 1
这些计时是使用Python3.6.0在一台相当古老的2GHz单核32位机器上获得的,该机器具有2GB的RAM,运行Linux的Debian派生版本。YMMV.你真的不想那样做。听起来你想要的是一个列表
,而不是一个数组。事实上,您不能在适当的位置附加到numpy
数组。不过,您可以创建一个全新的阵列。一个numpy
数组的主要限制是它的大小是固定的。我只是想加快我的数组循环。数组c[]太大。这就是为什么我想把我的值存储为整数对不起,我不明白你的意思c
不是数组,而是列表。什么数组循环?如果您想从列表c
中生成numpy.ndarray
,则只需执行a=np.array(c,np.int16)
numpy数组不是可扩展列表,而是固定大小的数组。有,但通常将数组设置为所需的大小,然后用数据填充。逐项扩展以添加新数据将非常低效。FWIW,即使是纯Python列表也不会逐项增长。在内部,CPython列表过度分配其数据存储,以便在需要分配更多空间之前可以追加多个项。它实际上并不存储你放进去的对象,它只存储对它们的引用。如果你能读懂C,你可以看到详细的注释,你真的不想这样做。听起来你想要的是一个列表
,而不是一个数组。事实上,您不能在适当的位置附加到numpy
数组。不过,您可以创建一个全新的阵列。一个numpy
数组的主要限制是它的大小是固定的。我只是想加快我的数组循环。数组c[]太大。这就是为什么我想把我的值存储为整数对不起,我没有