【问题标题】:Import CSV and create one list for each column in Python导入 CSV 并为 Python 中的每一列创建一个列表
【发布时间】:2016-10-15 19:15:49
【问题描述】:

我正在处理由逗号 (,) 分隔的 Python 中的 CSV 文件。

每一列都是一个采样参数,例如第 0 列是时间,每秒采样一次,第 1 列是海拔高度,每秒采样 4 次,等等。

所以列将如下所示:

Column 0 -> ["Time", 0, " "," "," ",1] 
Column 1 -> ["Altitude", 100, 200, 300, 400]

我正在尝试为每个列创建一个列表,以捕获其名称和所有数据。这样我就可以进行计算并将我的数据自动组织到一个新文件中(我正在处理的采样数据有大量的行)

我想对任何文件执行此操作,而不仅仅是一个文件,因此列数可能会有所不同。

通常,如果每个文件都是一致的,我会这样做:

import csv
time =[]
alt = []
dct = {}
with open('test.csv',"r") as csvfile:
    csv_f = csv.reader(csvfile)
    for row in csv_f:
        header.append(row[0])
        alt.append(row[1]) #etc for all columns

我是 python 的新手。如果不是更好的方法,这是解决这个问题的好方法吗?

感谢您的宝贵时间

【问题讨论】:

标签: python csv variables dynamic


【解决方案1】:

Pandas 可能最适合您。如果您使用 pandas 的 csv_read,它将基于该列创建一个 DataFrame。它大致是一个列表字典。

如果您特别想要一个列表,也可以使用 pandas 的 .tolist() 功能将其转换为列表。

import pandas as pd
data = pd.read_csv("soqn.csv")
dict_of_lists = {}

for column_name in data.columns:
    temp_list = data[column_name].tolist()
    dict_of_lists[column_name] = temp_list

print dict_of_lists

EDIT: 
dict_of_lists={column_name: data[column_name].tolist() for column_name in data.columns}
#This list comprehension might work faster.

【讨论】:

    【解决方案2】:

    我认为我让我的问题变得更简单,并且只专注于一栏。

    我最终想要做的是插值到最高采样率。所以这就是我想出的......如果我能做任何更有效率的事情,请告诉我。我在这个网站上使用了很多搜索来帮助构建它。我还是 Python 新手(大约 2-3 周,但有一些以前的编程经验)

    import csv
    header = []
    #initialize variables
    loc_int = 0
    loc_fin = 0
    temp_i = 0
    temp_f = 0
    
    with open('test2.csv',"r") as csvfile: # open csv file
        csv_f = csv.reader(csvfile)
        for row in csv_f:
            header.append(row[0]) #make a list that consists of all content in column A
    
    for x in range(0,len(header)-1): #go through entire column
    
        if header[x].isdigit() and header[x+1]=="": # find lower bound of sample to be interpolated
            loc_int = x
            temp_i = int(header[x])
    
        elif header[x+1].isdigit() and header[x]=="": # find upper bound of sample to be interpolated
    
            loc_fin = x
            temp_f = int(header[x+1])
    
        if temp_f>temp_i: #calculate interpolated values
            f_min_i = temp_f - temp_i
            interp = f_min_i/float((loc_fin+1)-loc_int)
    
            for y in range(loc_int, loc_fin+1):
                header[y] = temp_i + interp*(y-loc_int)
    
    print header
    
    with open("output.csv", 'wb') as g: #write to new file
        writer = csv.writer(g)
        for item in header:
            writer.writerow([item])
    

    我不知道如何用它的内插值编写我的新列表“标题”并将其替换为旧文件 test2.csv 的 A 列。

    非常感谢您的关注...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多