繁体   English   中英

从CSV文件PYTHON中读取列块

[英]Reading in column blocks from CSV file PYTHON

使用文件结构:

A   B    C    D
1   x    y    z
2   x    y    z
3   x    y    z
4   x    y    z
5   i    j    k
6   i    j    k
7   .......etc.

我想跳过标题,然后是每行的第一个元素。

真实的多汁数据是x,y,z,i,j,k值。

这些值是ADC值,需要排列到列表列表中。

my_list = [0] [x,x,x,x]
          [1] [y,y,y,y]
          [2] [z,z,z,z]
          [3] [i,i,i,i] etc.

我可以很容易地迭代一个完整的列,但棘手的部分是迭代每列的某些行。

我到目前为止尝试过:

def readin(myfile):

import csv
with open(myfile, 'r') as f:  # Open Results File

    next(f) # skip headings

    data = csv.reader(f, delimiter="\t")
    temp = []
    temp2=[]
    my_list=[]

    for i in range(13): #my_list will be 12 lists long
       print i
       for x in range(1,4):
        for row in data:
         temp.append(row[x])
    return my_list

我只是迭代了一列。 我不知道如何轻松切片(对于单独的x,我是等等)。

转置数据和切片:

 from itertools import izip
 data = csv.reader(f, delimiter="\t")
 trans = izip(*data)
 A = next(trans) # skip first col

这是代码,你可以看到我使用pandas来操纵我的数据。

import pandas as pd

df = pd.read_csv("te.txt")
df.drop(df.columns[[0]], axis=1, inplace=True) # delete the first column as you wished
li = []
for col in df.columns:
    li.append(list(df[col]))
print li

输出:

[['x', 'x', 'x', 'x', 'i', 'i'],
 ['y', 'y', 'y', 'y', 'j', 'j'],
 ['z', 'z', 'z', 'z', 'k', 'k']]

这是csv文件“te.txt”:

A,B,C,D
1,x,y,z
2,x,y,z
3,x,y,z
4,x,y,z
5,i,j,k
6,i,j,k

没有外部模块但csv

import csv

with open('blocks.csv') as infile:
    reader = csv.reader(infile)
    out_list = []

    # skip first line
    next(reader)

    while True:
        block = []
        try:
            # read four lines
            for i in range(4):
                block.append(next(reader))
        except StopIteration:
            break

        # transpose the block and skip the index column
        transposed_block = zip(*block)[1:]
        out_list += transposed_block

这会产生以下out_list

>>> out_list
[('x', 'x', 'x', 'x'),
 ('y', 'y', 'y', 'y'),
 ('z', 'z', 'z', 'z'),
 ('i', 'i', 'i', 'i'),
 ('j', 'j', 'j', 'j'),
 ('k', 'k', 'k', 'k')]

使用如下的熊猫:

from pandas import DataFrame as df

d = df.read_csv("text.txt")

d.drop(d.columns[[0]], axis=1, inplace=True)
k_list = [d.loc[:3,k].tolist() for k in d.columns()]

print k_list

输出:

[['x', 'x', 'x', 'x'], 
 ['y', 'y', 'y', 'y'],
 ['z', 'z', 'z', 'z']]

以下内容将为您提供所要求的结果。 它使用一种略微替代的方法一次读取四行,并删除第一列:

import csv

def readin(myfile):
    my_list = []

    with open(myfile, 'r') as f:        # Open Results File
        csv_input = csv.reader(f, delimiter=" ", skipinitialspace=True)
        headings = next(csv_input)      # Skip headings

        try:
            while True:
                my_list.extend(zip(next(csv_input), next(csv_input), next(csv_input), next(csv_input))[1:])
        except StopIteration:
            pass

    return my_list

result = readin("results_file.csv")

print result[0]
print result

输出是:

('x', 'x', 'x', 'x')

[('x', 'x', 'x', 'x'), ('y', 'y', 'y', 'y'), ('z', 'z', 'z', 'z'), ('i', 'i', 'i', 'i'), ('j', 'j', 'j', 'j'), ('k', 'k', 'k', 'k')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM