我正在从
CSV
文件读取数据,该文件类似于下面的矩阵/数组
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
我想将每个大于 1 的元素的索引更改为数组列表中的新行
这将使上面的数组如下所示
b = [[1,2],[5,6],[9,10],[3,4],[7,8][11,12]]
我在Python中做了什么(但无法得到答案)
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
c = b
rows = len(b)
columns = len(b[0])
c[4].append(1)
count = 3
for i in range(rows):
for j in range(columns):
if i > 1:
for k in columns
list1 =
c.insert(count,list1)
count = count + 1
您可以使用
numpy
。最后执行 indexing
和 concatenate
:
import numpy as np
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(np.concatenate((b[:,:2], b[:,2:])))
# [[ 1 2]
# [ 5 6]
# [ 9 10]
# [ 3 4]
# [ 7 8]
# [11 12]]
data =[]
data.append(['a',1])
data.append(['b',2])
data.append(['c',3])
data.append(['d',4])
print(data)
[['a', 1], ['b', 2], ['c', 3], ['d', 4]]
np.array(b).reshape(-1,2)
:import numpy as np
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
np.array(b).reshape(-1,2)
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])
为什么不将其分成两个列表,然后重新组合它们?
new_elements = []
for i in range(len(b)):
if len(b[i]) > 2:
new_elements.append(b[i][2:])
b[i] = b[i][:2]
b.extend(new_elements)
您可能想使用 numpy 数组和 concatenate 函数。
import numpy as np
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # or b = np.array(b)
c = np.concatenate((b[:, :2], b[:, 2:]),0)
如果您更喜欢使用 python 数组,您可以使用列表解释:
c = [row[:2] for row in b]
c.extend([row[2:] for row in b])
返回
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
使用列表理解。
例如:
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
n = 2
b = [j[i:i+n] for j in b for i in range(0, len(j), n)]
b = b[0::2] + b[1::2]
print(b)
输出:
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
另一种方法是这样的:
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
step = 2
length = len(b[0])
b = [elem[i:i+step] for i in range(0,length,step) for elem in b]
print(b)
输出:
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
使用
numpy.expand_dims()
多一个轴并沿该轴附加 2D 数组。
a1=np.expand_dims(np.array(np.arange(4).reshape(2,-1))+0,0)
a2=np.expand_dims(np.array(np.arange(4).reshape(2,-1))+10,0)
a1_a2=np.concatenate([a1,a2],axis=0)
结果显示为 print(a1_a2):
array([[[ 0, 1],
[ 2, 3]],
[[10, 11],
[12, 13]]])