gpt4 book ai didi

Python:如何根据第一列以外的列对 csv 文件进行切片?

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:48 25 4
gpt4 key购买 nike

我有一个 csv 文件,其中显示许多列和近 500000 行。我需要根据第二列(显示年份)对该文件进行切片,并保留所有其他列:

COL1   COL2   COL3   COL4   COL5   COL6   COL7
xxx 1986 xxx xxx xxx xxx xxx
xxx 1992 xxx xxx xxx xxx xxx
xxx 1998 xxx xxx xxx xxx xxx
... ... ... ... ... ... ...
xxx 2015 xxx xxx xxx xxx xxx
xxx 1984 xxx xxx xxx xxx xxx

我的问题:如何从中生成另一个 csv 文件,其中第二列中的值为 >=1992

期望的输出:

COL1   COL2   COL3   COL4   COL5   COL6   COL7
xxx 1992 xxx xxx xxx xxx xxx
xxx 1998 xxx xxx xxx xxx xxx
xxx 2015 xxx xxx xxx xxx xxx

我的尝试是这样的,但我陷入了应该插入链接到第二列的 if 的位置,但我不知道该怎么做:

from __future__ import division
import numpy
from numpy import *
import csv
from collections import *
import os
import glob

directoryPath=raw_input('Working directory: ') #Indicates where the csv file is located
for i,file in enumerate(os.listdir(directoryPath)): #Loops over the folder where the csv files are
if file.endswith(".csv"): #Checks if they are csv files
filename=os.path.basename(file) #Takes the complete path to the file
filelabel=file #Takes the filename only
strPath = os.path.join(directoryPath, file) #Retrieves the complete path to find the csv file
x=numpy.genfromtxt(strPath, delimiter=',')[:,7] #I GOT STUCK HERE

最佳答案

您可以迭代 CSV 的行,查看 COL2 中的值是否 >= 您感兴趣的年份。如果是,只需将该行添加到新列表中即可。将新列表传递给 CSV 编写器。您可以循环调用该函数,为所有以 csv 扩展名结尾的文件创建新的 CSV。

您必须传递working_directory年份。这是您要处理的 CSV 的文件夹。

import csv
import os
def make_csv(in_file, out_file, year):
with open(in_file, 'rb') as csv_in_file:
csv_row_list = []
first_row = True
csv_reader = csv.reader(csv_in_file)
for row in csv_reader:
if first_row:
csv_row_list.append(row)
first_row = False
else:
if int(row[1]) >= year:
csv_row_list.append(row)

with open(out_file, 'wb') as csv_out_file:
csv_writer = csv.writer(csv_out_file)
csv_writer.writerows(csv_row_list)

for root, directories, files in os.walk(working_directory):
for f in files:
if f.endswith('.csv'):
in_file = os.path.join(root, f)
out_file = os.path.join(root, os.path.splitext(f)[0] + '_new' + os.path.splitext(f)[1])
make_csv(in_file, out_file, year)

关于Python:如何根据第一列以外的列对 csv 文件进行切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com