如何将数据列分配给变量

How to assign columns of data to variables

我正在编写一个通用程序来读取和绘制 .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

我看到有人说 pandas 对这类事情有好处,但我似乎无法导入它。我更喜欢没有它的解决方案。

Pandas 实际上是正确的解决方案。问题是,为了稳健地处理你不确定底层结构的事情,你必须注意很多边缘情况,并试图将它塞进 csv 模块是一个头痛的秘方(虽然可以做到)

至于为什么你不能导入 pandas 的原因是默认情况下它没有附带 python。选择一门语言时要考虑的最重要的事情之一是它允许您访问的包生态系统。 Python 恰好是这方面最好的之一,所以忽略所有不属于标准的部分 python 就是忽略语言中最好的部分。

如果您在 windows 环境中,您应该先设置 conda。这将使您能够以很少的开销无缝地探索 python 用户可用的许多包。这包括pandas,这实际上是处理这个问题的正确方法。有关安装 conda 的更多信息,请参阅此 link:http://conda.pydata.org/docs/install/quick.html

安装 pandas 后,就这么简单:

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

就这么简单。

如果你真的,真的不想使用核心之外的东西 python 那么你可以用下面的东西来做,但是你没有给出足够的细节来说明实际情况解决方案:

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)]

好吧,您可以使用 csv 模块,前提是行内有某种分隔符来设置列的分隔符。

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