2017-03-08 46 views
0

具体来说,我在问如何从文本文件中取几列并将它们输入到一个数组中,而无需单独指定每列。在Python中指定列的范围

1 2 1 4.151E-12 4.553E-12 4.600E-12 4.852E-12 6.173E-12 7.756E-12 9.383E-12 1.096E-11 1.243E-11 1.379E-11 1.504E-11 1.619E-11 1.724E-11 2.139E-11 2.426E-11 2.791E-11 3.009E-11 3.152E-11 3.252E-11 3.326E-11 3.382E-11 3.426E-11 3.462E-11 3.572E-11 3.640E-11 3.698E-11 3.752E-11 
2 3 1 1.433E-12 1.655E-12 1.907E-12 2.014E-12 2.282E-12 2.682E-12 3.159E-12 3.685E-12 4.246E-12 4.833E-12 5.440E-12 6.059E-12 6.688E-12 9.845E-12 1.285E-11 1.810E-11 2.238E-11 2.590E-11 2.886E-11 3.139E-11 3.359E-11 3.552E-11 3.724E-11 4.375E-11 4.832E-11 5.192E-11 5.486E-11 

例如,我想这个数据本身以阵列设置的第二列,并且我本身要在阵列中的第三列。但是,我希望第四列通过按列分隔的数组中的最后一列。我不知道如何做到这一点,没有指定每个单独的列。

+0

毫无疑问,有一个模块,将为您做这个,例如熊猫包可以做到这一点,我认为。如果你想自己写:从磁盘读取文件,这将按行为您提供数据,现在将这些行转换为列,这很容易。 – Elmex80s

+1

如果它是全部数字数据,你可以看看'data = numpy.genfromtxt(file,unpack = True);第二数据= [1];第三=数据[2]; fourtoend =数据[3:]'。不确定Python标准库中是否有类似的功能。 – Wisperwind

回答

0

既然你提到一个文本文件,我要去把它作为内容是从文本文件获取一行一行:

with open("data.txt") as f: 
    for line in f: 
     data = line.split() 

     # I want the second column of this data set in an array by itself 
     second_column = data[1] 

     # I want the third column in an array by itself 
     third_column = data[2] 

     # I want column four through the last column in arrays that are separated by column 
     fourth_to_last_column = data[3:] 

如果然后打印second_columnthird_column和第一fourth_to_last_column行/输入,它看起来像这样:

2 
1 
['4.151E-12', '4.553E-12', '4.600E-12', '4.852E-12', '6.173E-12', '7.756E-12', '9.383E-12', '1.096E-11', '1.243E-11', '1.379E-11', '1.504E-11', '1.619E-11', '1.724E-11', '2.139E-11', '2.426E-11', '2.791E-11', '3.009E-11', '3.152E-11', '3.252E-11', '3.326E-11', '3.382E-11', '3.426E-11', '3.462E-11', '3.572E-11', '3.640E-11', '3.698E-11', '3.752E-11']