如何将数据列分配给变量

如何将数据列分配给变量

问题描述:

我正在编写一个通用程序来读取和绘制来自.txt文件的大量数据。每个文件都有不同数量的列。我知道每个文件都有8个我不感兴趣的列,所以我可以通过这种方式计算出相关列的数量。我如何读取数据并将每个相关列的数据分类到单独的变量中?如何将数据列分配给变量

这是我到目前为止有:

datafile = 'plotspecies.txt' 
with open(datafile) as file: 
    reader = csv.reader(file, delimiter=' ', skipinitialspace=True) 
    first_row = next(reader) 
    num_cols = len(first_row) 
    rows = csv.reader(file, delimiter = ' ', quotechar = '"') 
    data = [data for data in rows] 

num_species = num_cols - 8 

我见过的人说,大熊猫有利于这样的事情,但我似乎无法将其导入。我更喜欢没有它的解决方案。

+0

你想完全排序? –

+0

来自每列的数据,以便我可以将每个物种作为单个变量进行处理。 – evtoh

+0

你能提供一行的例子吗?或者给我们提供关于该文件的任何细节?没有这个答案很难回答。 –

熊猫在这里其实是正确的解决方案。问题是,为了强有力地处理一些你不确定底层结构的东西,你需要注意很多边缘情况,并试图将它们放入csv模块中,这是头痛的一个方法(尽管它可以完成)

至于为什么你不能导入pandas原因是它不默认与python来。选择语言时需要考虑的最重要的事情之一是它可以访问的软件包生态系统。 Python在这方面恰好是最好的之一,所以忽略不属于标准python的一切就是忽略语言的最佳部分。

如果你在一个Windows环境,你应该开始设置conda。这将允许您以很少的开销无缝探索python用户可用的许多软件包。这包括pandas,这实际上是解决这个问题的正确方法。查看安装畅达这个链接获取更多信息:http://conda.pydata.org/docs/install/quick.html

一旦你得到了pandas安装它,因为这很容易:

import pandas 
test = pandas.read_csv(<your_file>) 
your_Variable = test[<column_header>] 

易为。

如果你真的,真的不希望使用的东西并不在核心蟒蛇那么你就可以像下文中做到这一点,但是你有没有给予足够的细节一个实际的解决方案:

def col_var(input_file, delimiter): 
    # get each line into a variable 
    rows = open(input_file).read().splitlines() 

    # split each row into entries 
    split_rows = [row.split(delimiter) for row in rows] 

    # Re-orient your list 
    columns = zip(*split_rows) 

最低直观的一块,这是最后一行,所以这里是你展示它是如何工作的一个小例子:

>>> test = [[1,2], [3,4]] 
>>> zip(*test) 
[(1, 3), (2, 4)] 
+0

我在OS X上。我安装了Anaconda,但是我无法从中获取熊猫。我很可能做错了事。 – evtoh

+0

如果你在OS X上,那么你不必费心使用'conda'。只需使用'pip'。我发现点子比“conda”要容易得多,没有麻烦。 HTTPS://pip.pypa。io/en/stable /安装/ –

+0

如果我使用pip,它会返回一个错误,说我没有权限。 – evtoh

那么,你可以使用CSV模块提供有某种分隔符的内设置列appart的行。

import csv 

file_to_read_from = 'myFile.txt' 

#initializing as many lists as the columns you want (not all) 
col1, col2, col3 = [], [], [] 
with open(file_to_read_from, 'r') as file_in: 
    reader = csv.reader(file_in, delimiter=';') #might as well be ',', '\t' etc 
    for row in reader: 
     col1.append(row[0]) # assuming col 1 in the file is one of the 3 you want 
     col2.append(row[3]) # assuming col 4 in the file is one of the 3 you want 
     col3.append(row[5]) # assuming col 6 in the file is one of the 3 you want