使用2D数据帧



我得到了一个列为"起点站"one_answers"终点站"的数据集我正在尝试创建一个新列表,其中列表的每个元素都包含一个来自"起点桩号",一个来自于"终点桩号"。之后,在具有最大频率的新列表中找到元素

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

您可以尝试:

# using pandas iterrows
trip=[]          
for ix, row in df.iterrows():    
trip.append((row['Start Station'], row['End Station']))     
print(max(trip,key=trip.count)) 

最新更新