[英]Use csv.reader to read a file into a list but skip a specific column (Python)
Hello and thanks in advance for any help.您好,并在此先感谢您的帮助。 I am new to Python and I've found and tried many solutions but I can't seem to get the correct output.
我是 Python 新手,我找到并尝试了很多解决方案,但似乎无法获得正确的输出。
I have a csv file with several columns.我有一个包含几列的 csv 文件。 I want to skip the field names/first row and then read the file into a list.
我想跳过字段名称/第一行,然后将文件读入列表。 I also want to skip a column resulting in something like: column 1, column 2, column 3, column 5... I want do this because I am merging two other csv files (that are converted to lists) and they have different structures.
我还想跳过一列,结果如下:第 1 列、第 2 列、第 3 列、第 5 列...我想这样做是因为我正在合并另外两个 csv 文件(已转换为列表)并且它们具有不同的结构.
Here's my original code before I discovered the csv files had different structures...这是我发现 csv 文件具有不同结构之前的原始代码...
#convert input file1 to list
reader = csv.reader(file1,delimiter=',')
next(reader)
list_1 = []
list_1 = list(reader)
I have tried:我试过了:
reader = csv.reader(file1,delimiter=',')
next(reader)
included_cols = [0, 1, 2, 3, 5, 6, 7]
for row in reader:
content = list(row[i] for i in included_cols)
list_1 = list(content)
But this doesn't output correctly down the line when I merge the three lists into a sorted list like so:但是当我将三个列表合并到一个排序列表中时,这不会正确输出,如下所示:
unsortedList = list_1 + list_2 + list_3
and then I create a sorted list:然后我创建一个排序列表:
sortedList = sorted(unsortedList,key=operator.itemgetter(0))
and try to output the file like this:并尝试像这样输出文件:
with open('output.csv','a') as result_file:
wr = csv.writer(result_file, dialect='excel')
wr.writerows(sortedList)
The resulting output: weird at the top结果输出:顶部很奇怪
In general, I would use pandas instead.一般来说,我会改用熊猫。 Say you have the CSV file called
test.csv
:假设您有一个名为
test.csv
的 CSV 文件:
a,b,c,d
1,2,3,4
5,6,7,8
We can read it using pandas:我们可以使用pandas来读取它:
import itertools
import pandas as pd
df = pd.read_csv('test.csv', skiprows=[0], usecols=[0,1,3], header=None)
print(df)
0 1 3
0 1 2 4
1 5 6 8
Then, you can generate the lists from rows as:然后,您可以从行生成列表:
lists = df.values.tolist()
And finally into a single list:最后变成一个列表:
merged = list(itertools.chain(*lists))
print(merged)
[1, 2, 4, 5, 6, 8]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.