我有一个csv文件。第一列是user_id。
例如:
User_ID Latitude Longitude
1 55.75672775 37.61538506
1 55.75286376 37.62190819
1 47.60760975 -122.334137
1 40.74881754 -73.99116039
2 40.72046126 -74.00974274
2 41.56305944 -70.65380573
2 41.56302733 -70.65389156
2 41.5542606 -70.60093403
2 44.55035619 -69.63040352
我想为每个唯一用户运行一些功能。说,记录用户拥有的所有位置。所以我想做这样的事情:
For each user_id:
For row in all the rows of this user:
Do something
print user_id, result_output
我不知道如何实现这一目标。
有人可以帮助我吗?
使用DictReader
中CSV
模块的结果结合起来,然后播放:
import csv
data = {}
with open('filepath', 'r') as input:
reader = csv.DictReader(input)
for row in reader:
try:
data[row['user_id']].append((row['Latitude'], row['Longitude']))
Except KeyError:
data[row['User_ID'] = [(row['Latitude'], row['Longitude'])]
for user_id in data:
# do stuff with your tuples of longs and lats for each user_id
在DictReader
需要你的第一行,并将其作为每列的密钥。
使用此命令,我们可以使用键作为用户ID并使用列表作为值来做字典。每次遇到user_id时,您都从那里仅将long和lats的元组附加到用户列表。
如果您的定界符不是逗号,则将delimter
参数添加到中DictReader
。例如:
reader = DictReader(file, delimiter='\t')
并确保您使用的键正是Python在标头中找到的键(可能存在多余的空格,大小写差异等)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句