我有一个包含“起始站”和“结束站”列的数据集 我正在尝试创建一个新列表,其中列表的每个元素都包含 一个来自“起始站”,另一个来自“结束站”。 之后,在频率最高的新列表中找到一个元素
trip=[] #making list
for i in range(len(df)): #loop till end
trip.append((df['Start Station'][i],df['End Station'][i])) #adding pairs in new list
print(max(trip,key=trip.count))
问题:这段代码在jupyter笔记本中正常工作,但是当我尝试在其他地方显示错误
error:
trip.append((df['Start Station'][i],df['End Station'][i]))
File "/opt/conda/lib/python3.6/site-packages/pandas/core/series.py", line 601, in __getitem__
result = self.index.get_value(self, key)
File "/opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2477, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 98, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4404)
File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4087)
File "pandas/_libs/index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5126)
File "pandas/_libs/hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:14031)
File "pandas/_libs/hashtable_class_helper.pxi", line 765, in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13975)
KeyError: 0
答案 0 :(得分:0)
您可以尝试:
# using pandas iterrows
trip=[]
for ix, row in df.iterrows():
trip.append((row['Start Station'], row['End Station']))
print(max(trip,key=trip.count))