使用 python 读取数据集的特定列



我一直在尝试获取一个非常大的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 是由用户选择的,名称是特定列名称的数组。该程序在 2 小时左右后继续运行。作为参考,大约有 24,000 行数据和大约 5000 列。现在最后,如何通过不包括具有特定值(例如 -5(的列来减少列的数量?

我想,您只想将文件file_path的内容复制到reduced.csv中,并删除所有列,这些列以字符之一开头XPW并且没有列SCH_IDSTRAT_IDSTU_ID.

如果是这样,你可以像这样对熊猫这样做:

import pandas as pd
# read the first row only to get the column names
df= pd.read_csv(file_path, sep=',', dtype='str', nrows=1)
use_cols= [col for col in df.columns if col[:1] not in 'XPW' and col not in ['SCH_ID', 'STRAT_ID', 'STU_ID']]
df= pd.read_csv(file_path, sep=',', dtype='str', usecols=use_cols)
df.to_csv('reduced.csv', index=False, sep=',')

请将此视为伪代码,因为我不可能在没有数据的情况下对其进行测试,但我很有信心它可以工作。如果事实证明引用不是您喜欢的,您可以尝试将quotechar关键字添加到read_csvto_csv中。

顺便说一句,如果你想简化你的代码并使用with来确保你的文件在任何情况下都是关闭的,你可以重写你的最后一个while循环,如下所示:

with open('reduced.csv','w') as wfile:
for i, line in enumerate(redfile):
redarray = list(line.split(','))
line1 = ''
if i == 0:
for ii, token in enumerate(redarray):
if token in names:
nameind.append(ii)
line0= line0 + token + ','
line0 = line0[:-1]
print(line0)
wfile.write(line0)
wfile.write('n')
nameindarray = np.array(nameind)
elif i < 25000:
line1= ','.join([redarray[i] for i in nameind])
wfile.write(line1)
wfile.write('n')
else:
break

如果要切换到第二个建议,可能还需要在with子句中打开输入文件。如果使用with,则无需显式关闭文件。当with块终止时,此操作会自动为您完成。

最新更新