How to scrape weather data using meteostat library in python for multiple locations?

250 Views Asked by At

I am new to web scraping and trying to get familiar with meteostat library. I have the following dataset:

df = pd.DataFrame({
    'postal code': [11, 12, 13],
    'latitude': [40.7128, 34.0522, 51.5074],
    'longitude': [-74.0060, -118.2437, -0.1278]
})

What I want to do is to retrieve daily min and max temperature for these locations starting for the period from 01.01.2022 to 31.12.2022. I am trying the code below:

# Set time period
start = datetime(2022, 1, 1)
end = datetime(2022, 12, 31) 

# Create points for locations
df['point'] = df.apply(lambda x: Point(x['latitude'], x['longitude'], 70), 
                        axis=1)

# Get daily data for 2022
data = df.apply(lambda x: Daily(x['point'], start, end), 
                        axis=1)
data = data.fetch()

However, I receive the following error: AttributeError: 'Series' object has no attribute 'fetch'

1

There are 1 best solutions below

2
Ada On BEST ANSWER

You're applying the Daily() function to each row of the dataframe when you use df.apply(). This is creating a Series of Daily objects. Then you try to call fetch() on this series, but that doesn't work because you need to call it on a single Daily object (not a series of them).

You could try it like this:

data = []

for index, row in df.iterrows():
    point = Point(row['latitude'], row['longitude'])
    
    daily_data = Daily(point, start, end)
    daily_data = daily_data.fetch()

    data.append(daily_data)

# Concatenate the data from all locations into a single dataframe
result = pd.concat(data)

print(result)

If you also want to return the postal code column you can add this line in your for loop before appending the data to the list:

daily_data['postal code'] = row['postal code']