使用文件结构:
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' s等等。
答案 0 :(得分:2)
转置数据和切片:
from itertools import izip
data = csv.reader(f, delimiter="\t")
trans = izip(*data)
A = next(trans) # skip first col
答案 1 :(得分:1)
这是代码,你可以看到我使用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文件&#34; te.txt&#34;:
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
答案 2 :(得分:0)
没有外部模块的方法,但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')]
答案 3 :(得分:0)
使用pandas如下:
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']]
答案 4 :(得分:0)
以下内容将为您提供所要求的结果。它使用一种稍微替代的方法一次读取四行,并删除第一列:
CGRect frame = myView.frame;
frame.size.width = 100;
myView.frame = frame;
输出结果为:
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