我有一个采用以下格式的大型 .csv 文件:
“字符串 1”、“字符串 2”、“字符串 3”、“字符串 4”、“字符串 5”、“字符串 6”等
我有兴趣从列中提取信息,只要它链接到以下列即可。
举一个更清楚的例子,假设第 3 列和第 4 列由团队组成,它们代表他们的主办者(第 3 列是本地团队)。
“第一”、“结果”、“费城”、“迈阿密”等
“第二”、“结果”、“达拉斯”、“克利夫兰”等
“第三”、“结果”、“迈阿密”、“克利夫兰”等
“第四”、“结果”、“克利夫兰”、“迈阿密”等
“第五”、“结果”、“达拉斯”、“费城”等
“第六”、“结果”、“克利夫兰”、“达拉斯”等
“第七”、“结果”、“迈阿密”、“费城”等
“第八”、“结果”、“费城”、“迈阿密”等
“第九”、“结果”、“克利夫兰”、“迈阿密”等
我想获得一个由他们主办的球队组成的列表,不重复
Cleveland hosts
Dallas
Miami
Dallas hosts
Cleveland
Philadelphia
Miami hosts
Cleveland
Philadelphia
Philadelphia hosts
Miami
之后,我想在一个文件中写入有关这两种模式的所有行,也就是说,如果我想查看克利夫兰和迈阿密之间的比赛,我希望有一个像这样的 .csv,
“第三”、“结果”、“迈阿密”、“克利夫兰”等
“第四”、“结果”、“克利夫兰”、“迈阿密”等
“第九”、“结果”、“克利夫兰”、“迈阿密”等
使用以下代码,我设法读取一列并将所有唯一元素存储在字典中,以便我稍后可以从那里选择一个单词。我可以对第 4 列执行相同的操作,并通过将参数 Wanted_Column 的值更改为 3 来重复代码
import csv
from collections import Counter, defaultdict, OrderedDict
Var = 1
Wanted_Column = 2 # Col I want to analyze
with open('file.csv', "rb") as inputfile:
data = csv.reader(inputfile)
seen = defaultdict(set)
countd = Counter(
row[Wanted_Column]
for row in data
if row[Wanted_Column] and row[Wanted_Column] not in seen[row[Var]] and not seen[row[Var]].add(row[Wanted_Column])
)
y = OrderedDict(sorted(countd.items(), key = lambda t: t[0]))
for line in y:
print line
结果是,
Cleveland
Dallas
Miami
Philadelphia
所以,我的问题是,我应该添加什么才能有双重条件并以我暴露的方式显示元素?
之后,为了在另一个文件中写入行,我得到了这段代码,
look_for = set([ELEMENT IN DICTIONARY])
with open('file.csv','rb') as inf, open('output_file.csv','wb') as outf:
incsv = csv.reader(inf, delimiter=',')
outcsv = csv.writer(outf, delimiter=',')
outcsv.writerows(row for row in incsv if row[Wanted_column] in look_for)
仅使用一个元素就可以很好地工作,但是当然,由于之前的条件没有明确定义,我不知道应该更改什么才能获得我想要的结果。
最佳答案
您可以使用集合字典来跟踪主办球队和独特的客队球队。这是一个例子。
import csv
# load the csv file
rows = [r for r in csv.reader(file('sample.csv','r'))]
# order preservation list
preserve_order = []
# track the schedule from the hosting team's point of view
hosting_teams = {}
# change the wanted column here
wanted_column = 3
for row in rows:
# strip out the double quotes
row = [c.replace('"','') for c in row]
the_host = row[2]
the_order = row[0]
preserve_order.append(the_order)
# create a dictionary with a unique set of visiting teams
host_schedule = hosting_teams.setdefault(the_host,set([]))
# add the team visit
visiting_team = row[wanted_column]
host_schedule.add((visiting_team,the_order))
output = []
for hosting_team,host_schedule in hosting_teams.items():
for visiting_team,the_order in host_schedule:
output.append([the_order,"Result",hosting_team,visiting_team])
output.sort(key=lambda x:preserve_order.index(x[0]))
csv.writer(file('output.csv','wb')).writerows(output)
关于python - 循环遍历 .csv 文件,条件位于不同列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863731/