How to extract and visualize data from OSM file in Python

前端 未结 1 1392
忘了有多久
忘了有多久 2021-01-06 17:38

I have downloaded an OpenStreetMap file on my desktop , and I have used my OSM file in the jupyter notebook.

My code:

import xml.et         


        
相关标签:
1条回答
  • 2021-01-06 18:42

    You can extract all the data from an .osm file through PyOsmium (A fast and flexible C++ library for working with OpenStreetMap data) and then handle it with Pandas:

    Code:

    import osmium as osm
    import pandas as pd
    
    class OSMHandler(osm.SimpleHandler):
        def __init__(self):
            osm.SimpleHandler.__init__(self)
            self.osm_data = []
    
        def tag_inventory(self, elem, elem_type):
            for tag in elem.tags:
                self.osm_data.append([elem_type, 
                                       elem.id, 
                                       elem.version,
                                       elem.visible,
                                       pd.Timestamp(elem.timestamp),
                                       elem.uid,
                                       elem.user,
                                       elem.changeset,
                                       len(elem.tags),
                                       tag.k, 
                                       tag.v])
    
        def node(self, n):
            self.tag_inventory(n, "node")
    
        def way(self, w):
            self.tag_inventory(w, "way")
    
        def relation(self, r):
            self.tag_inventory(r, "relation")
    
    
    osmhandler = OSMHandler()
    # scan the input file and fills the handler list accordingly
    osmhandler.apply_file("muenchen.osm")
    
    # transform the list into a pandas DataFrame
    data_colnames = ['type', 'id', 'version', 'visible', 'ts', 'uid',
                     'user', 'chgset', 'ntags', 'tagkey', 'tagvalue']
    df_osm = pd.DataFrame(osmhandler.osm_data, columns=data_colnames)
    df_osm = tag_genome.sort_values(by=['type', 'id', 'ts'])
    

    Output:

    0 讨论(0)
提交回复
热议问题