Oscar Fuentes
Oscar Fuentes

Reputation: 21

Loop only reads the first row

I have a loop to create a map with Folium, the input is a database "s", but it only reads the first line. Something is stopping the loop.

Maybe it's an Indentation problem.

The code works as follows, first we check if we have a downloaded photo in the directory, if it is correct, we use this photo for the Folium popup and add feature. If we don't have a photo, we scrape it, download the photo to the directory, use it for the popup and add a feature.

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

Upvotes: 0

Views: 363

Answers (1)

bruno
bruno

Reputation: 32596

it only reads the first line. Something is stopping the loop.

yes, the two returns, because your code is :

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

so in all cases you return in the first turn of the for.

Very probably return features must be after the for :

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

Upvotes: 2

Related Questions