插入数据库Geohash(haikou数据)

插入数据库Geohash(haikou数据)



from pygeohash import encode, decode
import plotly
import numpy as np
import pandas as pd
import math
from matplotlib.path import Path
import numpy as np
import plotly.offline as of
import plotly.graph_objs as go
import chart_studio.plotly as py
import numpy as np
import pandas as pd
import folium
import webbrowser
from folium.plugins import HeatMap
import datetime
import time
import pymysql.cursors
import decimal
import geohash


def mysql(id):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='xu19931026',
        db='hk_taxi',
        charset='utf8'
    )
    cursor = conn.cursor()  # 获取游标
    sql = "select CAST(starting_lng as CHAR(11)) as BeginLongitude,CAST(starting_lat as CHAR(10)) as BeginLatitude FROM haikou_1 where id=%s"  # sql语句
    cursor.execute(sql,id)
    result=cursor.fetchall()
    df=list(result)  #将元组转换为列表
    lon = []
    lat = []
    conn.close()#关闭数据库连接
    for point in df:
        lon.append(float(point[0]))  #将字符串的经纬度转换为float格式
        lat.append(float(point[1]))
    return lon,lat
def get_geohash(lon, lat):
    #生成Geohash
    geo = geohash.encode(lat, lon)  # precision=9可以加精度
    return geo
def get_geolist(lon,lat):  #根据MySQL出的经纬度生成Geohash
    p = []
    for i in range(len(lon)):
        result = get_geohash(lon[i],lat[i])
        p.append(result)
    return p
def geohashsql(geohash,id):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='xu19931026',
        db='hk_taxi',
        charset='utf8'
    )
    geohash=(" ".join(geohash)) #列表转换为字符串
    cursor = conn.cursor()  # 获取游标
    sql = "UPDATE haikou_1 SET geo=%s WHERE id=%s"  # sql语句
    cursor.execute(sql,(geohash,id))
    conn.commit() #不加这一句不执行
    conn.close()  # 关闭数据库连接
#id最大12374604最小是1
#departure_time 从2017-04-29 07:20:00到2017-11-01 07:20:00
if __name__ == "__main__":
    time_start = time.time()
    id = 1000
    while id < 12374605:
        lon,lat=mysql(id) # 获取MySQL里的经度,纬度,经度纬度组成的列表
        geohash1=get_geolist(lon,lat) # 根据经纬度获得geohash1列表
        geohashsql(geohash1,id)
        id += 1
        if id%50000==0:
            time_end = time.time()
            yongshi=time_end-time_start
            t=(12374604-id)/id*yongshi
            print('已经完成'+str(id)+'**已用时**'+str(yongshi)+'还需要'+str(t)+'******')
    print('处理完毕,请在数据库中查看')

要获取2022年海口气温图历史气温数据和趋势分析,可以通过以下步骤进行: 1. 获取历史气温数据 可以通过气象部门或者相关网站获取历史气温数据,比如中国气象局的官方网站。在这里,我们假设已经获取到了海口市过去几年的每月平均气温数据,保存在一个 CSV 文件中。可以使用 Python 的 Pandas 库读取这个文件: ```python import pandas as pd df = pd.read_csv('haikou_temp.csv') ``` 读取出来的数据是一个 DataFrame,每一行表示一个月份的气温数据,包括年份、月份和平均气温。可以使用 Matplotlib 绘制出这些数据的折线图,观察气温的变化趋势: ```python import matplotlib.pyplot as plt plt.plot(df['year_month'], df['temp']) plt.title('Haikou Average Temperature (2015-2021)') plt.xlabel('Year-Month') plt.ylabel('Temperature (℃)') plt.show() ``` 其中 `year_month` 列是年份和月份的组合,比如 "2015-01" 表示2015年1月份,`temp` 列是平均气温。 2. 进行趋势分析 可以使用 Python 的 Statsmodels 库进行趋势分析。首先需要对数据进行平稳性检验,看看是否具有稳定的均值和方差。可以使用 Augmented Dickey-Fuller (ADF) 检验来进行平稳性检验: ```python from statsmodels.tsa.stattools import adfuller result = adfuller(df['temp']) print(f'ADF Statistic: {result[0]}') print(f'p-value: {result[1]}') ``` 如果 p-value 小于 0.05,就可以认为数据具有稳定的均值和方差。如果不是,可以进行差分操作,将非平稳的时间序列转化为平稳的时间序列。可以使用 Python 的 `diff` 函数来进行差分: ```python df['temp_diff'] = df['temp'].diff() df.dropna(inplace=True) ``` 差分后的数据保存在 `temp_diff` 列中,然后可以对差分后的数据进行平稳性检验。 接下来可以使用 ARIMA 模型进行预测。ARIMA 模型是一种针对时间序列数据的建模方法,可以用来预测未来的趋势。 ```python from statsmodels.tsa.arima.model import ARIMA model = ARIMA(df['temp_diff'], order=(1, 1, 1)) result = model.fit() print(result.summary()) ``` 这里使用了 ARIMA 模型,参数 `order=(1, 1, 1)` 表示使用 ARIMA(p=1, d=1, q=1) 模型。模型拟合完成后,可以使用 `forecast` 函数进行预测: ```python forecast = result.forecast(steps=12) ``` 这里预测了未来 12 个月的气温数据。最后可以将历史数据和预测结果绘制在同一张图上,观察气温的变化趋势: ```python plt.plot(df['year_month'], df['temp'], label='Historical Data') plt.plot(forecast.index, forecast.values, label='Forecast') plt.title('Haikou Average Temperature Prediction (2022)') plt.xlabel('Year-Month') plt.ylabel('Temperature (℃)') plt.legend() plt.show() ``` 完整代码如下: ```python import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.stattools import adfuller from statsmodels.tsa.arima.model import ARIMA # 读取历史气温数据 df = pd.read_csv('haikou_temp.csv') # 绘制历史数据折线图 plt.plot(df['year_month'], df['temp']) plt.title('Haikou Average Temperature (2015-2021)') plt.xlabel('Year-Month') plt.ylabel('Temperature (℃)') plt.show() # 进行平稳性检验 result = adfuller(df['temp']) print(f'ADF Statistic: {result[0]}') print(f'p-value: {result[1]}') # 进行差分操作 df['temp_diff'] = df['temp'].diff() df.dropna(inplace=True) # 再次进行平稳性检验 result = adfuller(df['temp_diff']) print(f'ADF Statistic: {result[0]}') print(f'p-value: {result[1]}') # ARIMA 模型拟合 model = ARIMA(df['temp_diff'], order=(1, 1, 1)) result = model.fit() print(result.summary()) # 进行预测 forecast = result.forecast(steps=12) # 绘制历史数据和预测结果的折线图 plt.plot(df['year_month'], df['temp'], label='Historical Data') plt.plot(forecast.index, forecast.values, label='Forecast') plt.title('Haikou Average Temperature Prediction (2022)') plt.xlabel('Year-Month') plt.ylabel('Temperature (℃)') plt.legend() plt.show() ``` 需要注意的是,趋势分析的结果仅供参考,实际气温变化可能会受到多种因素的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值