如何将数据列分配给变量
问题描述:
我正在编写一个通用程序来读取和绘制来自.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
我见过的人说,大熊猫有利于这样的事情,但我似乎无法将其导入。我更喜欢没有它的解决方案。
答
熊猫在这里其实是正确的解决方案。问题是,为了强有力地处理一些你不确定底层结构的东西,你需要注意很多边缘情况,并试图将它们放入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)]
答
那么,你可以使用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
你想完全排序? –
来自每列的数据,以便我可以将每个物种作为单个变量进行处理。 – evtoh
你能提供一行的例子吗?或者给我们提供关于该文件的任何细节?没有这个答案很难回答。 –