提问人:brawwcs 提问时间:6/10/2023 更新时间:6/10/2023 访问量:50
Python:如何从 2D 数组中提取备用列到数组?
Python: How to extract alternate column to array from a 2D array?
问:
我是 python 优化问题的新手。我在 txt 文件中有一个数据集,想将数据提取到两个不同的数组中。 这 2 个数组来自数据集的备用列。
文本文件: test_data.txt
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
预期结果:
array1 = [[1,3,5],[2,4,6],[3,5,7]]
array2 = [[2,4,6],[3,5,7],[4,6,8]]
下面的代码是我所做的,我能够提取整个表,但由于类型错误而无法提取备用列。
with open("test_data.txt","r") as test_table:
array=[]
for line in test_table:
array.append([int(x) for x in line.split()])
array1=array[:,0::2]
array2=array[:,1::2]
谢谢!
答:
0赞
Domiziano Scarcelli
6/10/2023
#1
如果你想保持你的语法,你必须使用 ,因为这不是 python list 的有效语法。此代码将按您的意愿工作:numpy
import numpy as np
with open("test_data.txt", "r") as test_table:
array = []
for line in test_table:
array.append([int(x) for x in line.split()])
array = np.array(array)
array1 = array[:, 0::2]
array2 = array[:, 1::2]
否则,如果您不想使用 ,您可以利用列表推导式:numpy
with open("test_data.txt", "r") as test_table:
array = []
for line in test_table:
array.append([int(x) for x in line.split()])
array1 = [[row[i] for i in range(len(row)) if i % 2 == 0] for row in array]
array2 = [[row[i] for i in range(len(row)) if i % 2 != 0] for row in array]
1赞
Anass Ibrahimi
6/10/2023
#2
您遇到的类型错误是因为是常规数组/列表,而不是 NumPy 数组。因此,不能将类似 NumPy 的索引语法与常规数组一起使用。若要解决此问题,有以下几个选项:array
选项 1:将数组转换为 NumPy 数组
如果您更喜欢使用 NumPy 数组,您可以使用 np.array() 函数将数组转换为 NumPy 数组。下面是一个示例:
import numpy as np
with open("test_data.txt","r") as test_table:
array=[]
for line in test_table:
array.append([int(x) for x in line.split()])
array = np.array(array)
array1=array[:,0::2]
array2=array[:,1::2]
现在,您可以使用 NumPy 索引语法并访问所需的元素。array[:, 0::2]
array[:, 1::2]
选项 2:使用常规数组
如果您希望继续使用常规数组,则可以使用列表推导式获得类似的结果。下面是一个示例:
with open("test_data.txt","r") as test_table:
array=[]
for line in test_table:
array.append([int(x) for x in line.split()])
array1 = [row[0::2] for row in array]
array2 = [row[1::2] for row in array]
在本例中,将包含数组的每个子列表中偶数索引处的元素,并将包含每个子列表中奇数索引处的元素。array1
array2
0赞
AliAhmed
6/10/2023
#3
如果你使用numpy,这很容易
import numpy as np
array =[[1,2,3,4,5,6],
[2,3,4,5,6,7],
[3,4,5,6,7,8]]
arr = np.asarray(array)
print(arr[:][:,0::2])
print(arr[:][:,1::2])
没有 numpy
arr2 = [i[0::2] for i in array]
print(arr2)
评论