Может импортировать в mongoDB Pandas Dataframe данных о погоде со столбцами широты и долготы, но Compass не распознает их как координаты - PullRequest
0 голосов
/ 31 марта 2019

Я пытаюсь импортировать pandas Dataframe со столбцами широты и долготы в mongoDB, используя python. Я могу импортировать Dataframe, но столбцы Lat и Long просто читаются как целые числа, а не координаты.

Я могу заставить Datafame импортировать в mongoDB, но компас не генерирует карту для столбцов широты и долготы. Он обрабатывает столбцы как числа.

enter image description here

Затем я узнал, что Монго использует GeoJSON для координатных данных. см. ссылку: https://docs.mongodb.com/manual/reference/geojson/

Итак, я извлек столбцы lat и long и преобразовал их в файл GeoJSON с идентификатором станции в свойствах.

dfm.head()

    Station ID  latitude    longitude
0   53179          62.41    -140.87
1   53178          62.41    -140.87
2   1518           62.41    -140.87
3   6848           62.37    -140.87
4   10192          61.37    -139.03

Затем я обнаружил, что эта функция преобразует кадр данных pandas в файл GeoJSON (нет моей работы)


def df_to_geojson(df, properties, lat='latitude', lon='longitude'):
    """
    Turn a dataframe containing point data into a geojson formatted python dictionary

    df : the dataframe to convert to geojson
    properties : a list of columns in the dataframe to turn into geojson feature properties
    lat : the name of the column in the dataframe that contains latitude data
    lon : the name of the column in the dataframe that contains longitude data
    """

    # create a new python dict to contain our geojson data, using geojson format
    geojson = {'type':'FeatureCollection', 'features':[]}

    # loop through each row in the dataframe and convert each row to geojson format
    for _, row in df.iterrows():
        # create a feature template to fill in
        feature = {'type':'Feature',
                   'properties':{},
                   'geometry':{'type':'Point',
                               'coordinates':[]}}

        # fill in the coordinates
        feature['geometry']['coordinates'] = [row[lon],row[lat]]

        # for each column, get the value and add it as a new feature property
        for prop in properties:
            feature['properties'][prop] = row[prop]

        # add this feature (aka, converted dataframe row) to the list of features inside our dict
        geojson['features'].append(feature)

    return geojson

так что после использования функции на dfm вот так

useful_columns = ['Station ID']
geojson_dict = df_to_geojson(dfm, properties=useful_columns)
geojson_str = json.dumps(geojson_dict, indent=2)

Я получаю файл GeoJSON, который выглядит следующим образом, только первые 2 записи.

var dataset = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "Station ID": 53179.0
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -140.87,
          62.41
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "Station ID": 53178.0
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -140.87,
          62.41
        ]
      }
    },

Когда я пытаюсь импортировать GeoJSON в mongoDB:

uri = "mongodb+srv://<<my connection string removed for security>>"
client = pymongo.MongoClient(uri)
db = client.Weather

vg = db.gps
vg.insert_many(geojson_str)

Я получаю эту ошибку:

document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

Что я хочу сделать, так это то, что я смогу преобразовать кадр данных pandas со столбцами широты и долготы, чтобы mongoDB и Compass интерпретировали их как координаты GPS, а не просто как еще одно целое число. Смотрите рисунок ниже для правильного примера данных координат в mongoDB.

MongoDB can perform geo-quires with this kind of coordinate information

...