我一直在尝试将一个非常大的csv文件读入python并编写一个新的简化csv文件。我已经创建了一个要使用的列名列表。下面是我尝试使用的代码
redfile = open(file_path,'r')
import csv
reader=csv.reader(redfile)
names=next(reader)
for elem in names:
if elem.startswith("W")==True:
names.remove(elem)
for elem in names:
if elem.startswith("P")==True:
names.remove(elem)
for elem in names:
if elem.startswith("X")==True:
names.remove(elem)
names.remove("SCH_ID")
names.remove("STRAT_ID")
names.remove("STU_ID")
nameind = []
line0 = ''
wfile = open('reduced.csv','w')
for i, line in enumerate(redfile):
redarray = [x for x in line.split(",")]
line1 = ''
if i == 0:
for ii in range(0,len(redarray)):
if redarray[ii] in names:
nameind.append(ii)
line0 = line0+redarray[ii]+','
line0 = line0[:-1]
print(line0)
wfile.write(line0)
wfile.write('\n')
nameindarray = np.array(nameind)
elif i < 25000:
for ii in nameind:
line1 = line1+redarray[ii]+','
line1 = line1[:-1]
wfile.write(line1)
wfile.write('\n')
else:
break
redfile.close()
wfile.close()
print(i)
如您所见,redfile是由用户选择的,names是一个特定列名的数组。程序在大约2小时后继续运行。作为参考,大约有24000行数据和5000列数据。最后,如何通过不包含具有特定值(如-5)的列来减少列的数量?你知道吗
我想,您只需要将文件
file_path
的内容复制到reduced.csv
,删除所有列,这些列以X
、P
、W
中的一个字符开头,而不包括SCH_ID
、STRAT_ID
、STU_ID
列。你知道吗如果是这样的话,你可以这样对待熊猫:
请认为这是伪代码,因为我没有可能测试它没有数据,但我很有信心它的工作。如果发现引号不是您喜欢的那样,您可以尝试将} 和^{} 。你知道吗
quotechar
关键字添加到^{顺便说一句,如果您想简化代码并使用
with
来确保文件在任何情况下都是关闭的,您可以重写上一个while循环,如下所示:如果您想切换到第二个方案,您可能还需要在
with
子句中打开输入文件。如果使用with
,则不需要显式地关闭文件。当with
块终止时,这将自动为您完成。你知道吗相关问题 更多 >
编程相关推荐