簡體   English   中英

循環只讀取第一行

[英]Loop only reads the first row

我有一個循環來用 Folium 創建一個 map,輸入是一個數據庫“s”,但它只讀取第一行。 有些東西正在停止循環。

也許這是一個縮進問題。

代碼如下,首先我們檢查目錄中是否有下載的照片,如果正確,我們將這張照片用於Folium彈出窗口並添加功能。 如果我們沒有照片,我們會抓取它,將照片下載到目錄中,將其用於彈出窗口並添加一個功能。

def create_geojson_features(s):

features = []

for _, row in s.iterrows():
    if os.path.isfile('/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg'):
        image = '/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg'
        print("photo OK!")
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['lon'],row['lat']]
            },
            'properties': {
                'time': pd.to_datetime(row['date']).__str__(),
                'popup': "<img src=" + image.__str__() + " width = '250' height='200'/>"+'<br>'+'<br>'+'Shipname: '+row['shipname'].__str__() +'<br>'+ 'MMSI: '+row['mmsi'].__str__() +'<br>' + 'Group: '+row['group'].__str__() +'<br>''Speed: '+row['speed'].__str__()+' knots',
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillColor'],
                    'fillOpacity': 0.8,
                    'radius': 5
                }
            }
        }
        features.append(feature)
        return features

    else:
        vessel_id = row['IMO']

        data = {
               "templates[]": [
                   "modal_validation_errors:0",
                   "modal_email_verificate:0",
                   "r_vessel_types_multi:0",
                   "r_positions_single:0",
                   "vessel_profile:0",
               ],
               "request[0][module]": "ships",
               "request[0][action]": "list",
               "request[0][id]": "0",
               "request[0][data][0][name]": "imo",
               "request[0][data][0][value]": vessel_id,
               "request[0][sort]": "",
               "request[0][limit]": "1",
               "request[0][stamp]": "0",
               "request[1][module]": "top_stat",
               "request[1][action]": "list",
               "request[1][id]": "0",
               "request[1][data]": "",
               "request[1][sort]": "",
               "request[1][limit]": "",
               "request[1][stamp]": "0",
               "dictionary[]": ["countrys:0", "vessel_types:0", "positions:0"],
        }
            
        data = requests.post("https://www.balticshipping.com/", data=data).json()
        try:
            image = data["data"]["request"][0]["ships"][0]["data"]["gallery"][0]["file"]
            headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
            local_file = open('/Users/Alberto/Desktop/Oscar/UNIVERSIDAD/TFG/test_inicial/out/IMO_photos/' + row['IMO'].__str__() + '.jpg','wb')
            req = Request(url=image, headers=headers)
            with urlopen(req) as response:
                local_file.write(response.read())
        except IndexError:
            image = 'null'
        print(image)
        feature = {
            'type': 'Feature',
            'geometry': {
                'type':'Point',
                'coordinates':[row['lon'],row['lat']]
            },
            'properties': {
                'time': pd.to_datetime(row['date']).__str__(),
                'popup': "<img src=" + image.__str__() + " width = '250' height='200'/>"+'<br>'+'<br>'+'Shipname: '+row['shipname'].__str__() +'<br>'+ 'MMSI: '+row['mmsi'].__str__() +'<br>' + 'Group: '+row['group'].__str__() +'<br>''Speed: '+row['speed'].__str__()+' knots',
                'style': {'color' : ''},
                'icon': 'circle',
                'iconstyle':{
                    'fillColor': row['fillColor'],
                    'fillOpacity': 0.8,
                    'radius': 5
                }
            }
        }
        features.append(feature)
        return features

它只讀取第一行。 有些東西正在停止循環。

是的,這兩個return ,因為您的代碼是:

for _, row in s.iterrows():
    if ...:
       ...
       return features
    else:
       ...
       return features

因此,在所有情況下,您都會在for的第一輪返回。

很可能return features必須for之后:

for _, row in s.iterrows():
    if ...:
       ...
       features.append(feature)
    else:
       ...
       features.append(feature)
return features

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM