如果我有一个CSV文件,每行有一个字典值(列为[“Location”],[“MovieDate”],[“Formatted_Address”],[“Lat”],[“Lng”] ),如果我想按Location
进行分组,并且追加共享相同MovieDate
值的所有Location
值,我会被告知使用OrderDict。
ex of data:
Location,MovieDate,Formatted_Address,Lat,Lng
"Edgebrook Park, Chicago ",Jun-7 A League of Their Own,"Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672
"Edgebrook Park, Chicago ","Jun-9 It's a Mad, Mad, Mad, Mad World","Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672
对于每个具有相同位置的行(如本示例中的^),我想像这样输出,以便没有重复的位置。
"Edgebrook Park, Chicago ","Jun-7 A League of Their Own Jun-9 It's a Mad, Mad, Mad, Mad World","Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672
使用ordereddict执行此操作的代码有什么问题?
from collections import OrderedDict
od = OrderedDict()
import csv
with open("MovieDictFormatted.csv") as f,open("MoviesCombined.csv" ,"w") as out:
r = csv.reader(f)
wr = csv.writer(out)
header = next(r)
for row in r:
loc,rest = row[0], row[1]
od.setdefault(loc, []).append(rest)
wr.writerow(header)
for loc,vals in od.items():
wr.writerow([loc]+vals)
我最终得到的是这样的:
['Edgebrook Park, Chicago ', 'Jun-7 A League of Their Own']
['Gage Park, Chicago ', "Jun-9 It's a Mad, Mad, Mad, Mad World"]
['Jefferson Memorial Park, Chicago ', 'Jun-12 Monsters University ', 'Jul-11 Frozen ', 'Aug-8 The Blues Brothers ']
['Commercial Club Playground, Chicago ', 'Jun-12 Despicable Me 2']
问题是我在这种情况下没有显示其他列,我最好怎么做?我还希望将MovieDate值设为一个长字符串,如下所示:
'Jun-12 Monsters University Jul-11 Frozen Aug-8 The Blues Brothers '
而不是:
'Jun-12 Monsters University ', 'Jul-11 Frozen ', 'Aug-8 The Blues Brothers '
谢谢你们,欣赏它。我是一个蟒蛇诺布。
遗憾的是,将row[0], row[1]
更改为row[0], row[1:]
并不能满足我的需求。我只想在第二列(MovieDate)中添加值,而不是复制所有其他列。 :
['Jefferson Memorial Park, Chicago ', ['Jun-12 Monsters University ', 'Jefferson Memorial Park, 4822 North Long Avenue, Chicago, IL 60630, USA', '41.76083920000001', '-87.6294353'], ['Jul-11 Frozen ', 'Jefferson Memorial Park, 4822 North Long Avenue, Chicago, IL 60630, USA', '41.76083920000001', '-87.6294353'], ['Aug-8 The Blues Brothers ', 'Jefferson Memorial Park, 4822 North Long Avenue, Chicago, IL 60630, USA', '41.76083920000001', '-87.6294353']]
答案 0 :(得分:1)
你只需要进行一些更改,你需要加入lat和long,去掉dupe lat和longs我们还需要使用它作为关键:
with open("data.csv") as f,open("new.csv" ,"w") as out:
r = csv.reader(f)
wr= csv.writer(out)
header = next(r)
for row in r:
od.setdefault((row[0], row[-2], row[-1]), []).append(" ".join(row[1:-2]))
wr.writerow(header)
for loc,vals in od.items():
wr.writerow([loc[0]] + vals+list(loc[1:]))
输出:
Location,MovieDate,Formatted_Address,Lat,Lng
"Edgebrook Park, Chicago ","Jun-7 A League of Their Own Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA","Jun-9 It's a Mad, Mad, Mad, Mad World Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672
A League of Their Own
首先是因为它出现在疯狂的疯狂行之前
row[1:-2]
获取所有内容,包括纬度,长度和位置,我们将lat和long存储在我们的密钥元组中,以避免在每行末尾重复写入。
使用名称和解压缩可能会让它更容易理解:
with open("data.csv") as f, open("new.csv", "w") as out:
r = csv.reader(f)
wr = csv.writer(out)
header = next(r)
for row in r:
loc, mov, form, lat, long = row
od.setdefault((loc, lat, long), []).append("{} {}".format(mov, form))
wr.writerow(header)
for loc, vals in od.items():
wr.writerow([loc[0]] + vals + list(loc[1:]))
使用csv.Dictwriter保留五列:
od = OrderedDict()
import csv
with open("data.csv") as f, open("new.csv", "w") as out:
r = csv.DictReader(f,fieldnames=['Location', 'MovieDate', 'Formatted_Address', 'Lat', 'Lng'])
wr = csv.DictWriter(out, fieldnames=r.fieldnames)
for row in r:
od.setdefault(row["Location"], dict(Location=row["Location"], Lat=row["Lat"], Lng=row["Lng"],
MovieDate=[], Formatted_Address=row["Formatted_Address"]))
od[row["Location"]]["MovieDate"].append(row["MovieDate"])
for loc, vals in od.items():
od[loc]["MovieDate"]= ", ".join(od[loc]["MovieDate"])
wr.writerow(vals)
# 输出:
"Edgebrook Park, Chicago ","Jun-7 A League of Their Own, Jun-9 It's a Mad, Mad, Mad, Mad World","Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672
因此,五列保持不变,我们将"MovieDate"
加入到单个字符串中,Formatted_Address=form
始终是唯一的,因此我们无需更新。
结果与您想要的相匹配我们需要做的就是连接MovieDate's
并删除位置,纬度,Lng和'Formatted_Address'
的重复条目。
答案 1 :(得分:0)
让我们尝试改变
od.setdefault(loc, []).append(rest)
要
od[loc] = ' '.join([od.get(loc, ''), ' 'join(rest)])
然后保持原样:
wr.writerow([loc]+vals)
答案 2 :(得分:-1)
假设location是该行的第一项:
dict = {}
for line in f:
if line[0] not in dict:
dict[line[0]] = []
dict[line[0]].append(line[1:])
对于每个位置,您都拥有行的其余部分
for key, value in dict.iteritems():
out.write(key + value)