12 ms·
Stop using zip codes for geospatial analysis (2019)
- deleted 2y ago[deleted]
- hammock 2y agoGreat article. Zip codes can be super expedient. But you have to be self aware that for many uses cases they function WORSE than a random grid. Because they have built-in aggregation of a central post office(and surrounding) with a certain radius of rural/less dense surrounding. So for example, if you are sorting “rural zips” vs “urban zips” it will only take you so far, and may actually be harmful. Same goes with MSAs/DMAs (media markets). These have to be used for buying media, but for geospatial analysis they are suboptimal for the same reasons. Easiest way to dip your toe into the water of something better is to start with A-D census counties.
- jihadjihad 2y agoTo put it in plain mathematical language, ZIP codes are not defined as polygons [0]. The consequence is that performing any analysis with an assumption that ZIP codes are polygons is bound to be error-prone. 0: https://manifold.net/doc/mfd8/zip_codes_are_not_areas.htm https://manifold.net/doc/mfd8/zip_codes_are_not_areas.htm
- mholt 2y agoYeah. ZIP codes are sets in the abstract-dimensional space of carrier delivery points. I suppose you could think of them as lines, but definitely not polygons.
- cogman10 2y agoZip codes (in the US) are machine readable numbers a mail sorter can use to send a parcel to the right delivery truck for final delivery. In the US, they represent the hierarchy of postal centers with the most significant digit representing the primary hub for a region and the smallest number the actual post office that will be in charge of delivering the letter (or truck if you do the extended post code). They don't represent geography at all, they represent the organizational structure of USPS. They work by making the address on a letter almost meaningless. For some smaller population zip codes you can practically just put the name and zip code down and achieve delivery.
- Spivak 2y agoRight but this ends up being a good approximation for geography because the reality of logistics is that you end up doing a cute n-ary search of the geography. When you know the regional hub you can say for certain a huge chunk of the US the zip code doesn't represent. And then you keep n-secting. Sometimes the land-mass you get at the end is specific enough for your uses. You're not going to wind up with a situation where zip codes with the same regional marker end up on different coasts.
- mattforrest 2y agoJust use a spatial query. That’s what they are made for.
- makeitdouble 2y ago> You're not going to wind up with a situation where zip codes with the same regional marker end up on different coasts. Couldn't this happen for military or proxy codes (PO boxes or other) ?
- alsodumb 2y agoI agree that they weren't explicitly meant to represent geography, but implicitly they do, right? Are there cases where this is violated? In other words, is it safe to assume that for entity in a zip code is less than x distance away from the closest entity in the same zip code?
- freyfogle 2y agoit is safe to assume nothing. Please see: https://opencagedata.com/guides/how-to-think-about-postcodes-and-geocoding https://opencagedata.com/guides/how-to-think-about-postcodes... I write this as someone who grew up in the ZIP code 09180
- makeitdouble 2y agoIt might be true, but does it help if the x varies from "on a nearby mountain" to "within a street block", and you sometimes have every habitants closer to another zip code than theirs ?
- mcphage 2y ago> The consequence is that performing any analysis with an assumption that ZIP codes are polygons is bound to be error-prone. Yeah, but any analysis you're likely to perform is approximate enough that the fact that ZIP codes aren't polygons is basically a rounding error. Plus, it's a lot easier to get ZIP codes, and they're more reliably correct, so you might still get better results, than you would going with another indicator that is either (a) less reliable or (b) less available.
- mattforrest 2y agoThey aren’t reliable correct actually. The boundaries that the Census publishes are called Zip Code Tabulation Areas which are approximations of zip codes and include overlaps.
- wombatpm 2y agoZCTA5 roughly corresponds to the area of a 5 digit zip code. Problem is there are large areas of the west that don’t have permanent residents and no mail delivery. Plus they change over time.
- NelsonMinar 2y agoThat's not the important problem and there's a simple solution with ZCTAs. The big problem is zip codes are defined in terms of convenient postal routes and aren't suitable for most geospatial analysis. Census units, as the article explains, are a much better choice.
- BiteCode_dev 2y agoYou ask a customer their census unit on purchase though.
- mattforrest 2y agoFunny to see this one pop up today (I wrote this one way back when) but I just refreshed it into a video on my channel: https://www.youtube.com/watch?v=x-opv4REEic https://www.youtube.com/watch?v=x-opv4REEic
- nancyp 2y agoInstead of zip use the following? Use Addresses Use Census Units Use your own Spatial Index Why not lat, long?
- ajfriend 2y agoIt depends on if you want to model a point or an area. lat/lng gives you a point, but you often want an area to, for example, count how many people are in that area. A spatial index like H3 provides a grid of area units.
- HappMacDonald 2y agoBut so do lat long ranges.
- ajfriend 2y agoYou can use those if they work for your application. One downside would be that you're storing 4 numbers compared to a single `int64` index with H3. You also have to decide how you'll do that binning. Can bins overlap? What do you do at the poles? H3 provides some reasonable default choices for you so don't have to worry about that part of your solution design.
- ww520 2y agoLat/lon is in a spherical coordinate. It’s more complicated to do calculation. Btw. I have a need recently to compute the shortest distance from a point to a line defined by two points, all in lat/lon. Anyone has any lead on how to do it?
- ajfriend 2y ago...and use H3 instead! https://h3geo.org/ https://h3geo.org/
- sbrother 2y agoVery different use case -- ZIPs/ZCTAs have some semblance of population normalization
- mattforrest 2y agoNot necessarily true. The population isn't balanced at all between many. Census units are.
- ellisv 2y agoAbsolutely this. Use other Census areal units if you can and ZCTAs only if you have to.
- ajfriend 2y agoIf you care about that and have a data source, you can add, for example, population density per H3 cell as part of your analysis. That has the additional benefit of denoting the this quantity of interest explicitly, rather than some implicitly assumed correlation which may not be true.
- ingenieroariel 2y agoHey AJ, this is almost on topic, do you know of a more up to date version of the dataset you used on the blog post release for H3 v4.0.0 [1]? They stopped updating in Oct 2023. Thanks! [1] https://data.humdata.org/dataset/kontur-population-dataset https://data.humdata.org/dataset/kontur-population-dataset
- ajfriend 2y agoI don't. And maybe I should have emphasized "and have a data source" more, since its doing a lot of the heavy-lifting in my statement :)
- jpjoi 2y agoZip codes are just weird to use for anything other than mail in general because they’re set up based off infrastructure. CGP Grey has a great video on this: https://m.youtube.com/watch?v=1K5oDtVAYzk https://m.youtube.com/watch?v=1K5oDtVAYzk
- diggan 2y agoI've noticed more and more super/hypermarkets started asking for your zip/postal code sometime during self-checkout. I'm guessing they use these as approximations about where people travel from, so they can evaluate if to open more stores closer to popular areas, or something like that. Pretty sure there is more use cases for postal codes too.
- paraboli 2y agoThey use bulk mail to send out flyers, coupons, and can use zip codes to AB test these.
- kjellsbells 2y agoPostcodes are very useful (but not perfect) proxies for household socioeconomic status, which is useful for marketing and sales analysis. That data linked with the payment method that the register collects pretty much gives the store exactly who you are and where you live even if you chose not to sign up to the store's loyalty program.
- Spivak 2y agoWait until you find out that this is the same way phones used to work. The number was the row/colum for the operator needed to plug your line into.
- paulddraper 2y agoPeople use ZIP codes because they have ZIP codes. No one has census blocks. And coordinates can work but lack some inherent advantages, such as human readability and a semblance of pop density normalization.
- funkaster 2y agoIf you want to learn a bit more, there was a recent, really good Planet Money episode[1] about this exact same topic. They focus on the problems that you might face when using zip code for demographic analysis. [1]: https://www.npr.org/2025/01/08/1223466587/zip-code-history https://www.npr.org/2025/01/08/1223466587/zip-code-history
- throw0101c 2y agoCGP Grey recently posted a video on Zip codes, "The Hidden Pattern in Post Codes": * https://www.youtube.com/watch?v=1K5oDtVAYzk https://www.youtube.com/watch?v=1K5oDtVAYzk
- Cthulhu_ 2y agoThat's what I was thinking of earlier, the succinct version is "your address is where mail needs to go, the zip code is how to get it there". Or in other words, the zip code is the address(es) of the sorting centers and post offices to the destination.
- jonas21 2y agoZIP codes are an emergent property of the mail delivery system. While the author might consider this a bad thing, this makes them "good enough" on multiple axes in practice. They tend to be: - Well-known (everybody knows their zip code) - Easily extracted (they're part of every address, no geocoding required) - Uniform-enough (not perfect, but in most cases close) - Granular-enough - Contiguous-enough by travel time Notably, the alternatives the author proposes all fail on one or more of these: - Census units: almost nobody knows what census tract they live in, and it can be non-trivial to map from address to tract - Spatial cells: uneven distribution of population, and arbitrary division of space (boundaries pass right through buildings), and definitely nobody knows what S2 or H3 cell they live in. - Address: this option doesn't even make sense. Yes, you can geocode addresses, but you still need to aggregate by something.
- mattforrest 2y agoWell you hit on all the points that discuss the compromises that zip codes offer. Just because you have them in your data doesn't mean that they can produce anything useful. You are correct that no one knows their census unit is (if you are thinking from someone entering this on a website) but collecting location or address will be a lot better. Fact is a lot of web data contains a zip but if you can collect something better it will usually render better results. Unless you are analyzing shipments then that is fine.
- ellisv 2y agoThere are point process models, but, yes, its much more common to want to aggregate to a spatial area. Another consideration is what kind of reference information is available at different spatial units. There are plenty of Census Bureau data available by ZCTA but some data may only be available at other aggregate units. Zip Codes are often used as political boundaries. I'd also mention the "best" areal unit depends on the data. There is a well known phenomenon called the modifiable areal unit problem in which spatial effects appear and vanish at different spatial resolutions. It can sort of be thought of as a spatial variation of the ecological fallacy.
- ericrallen 2y agoThis is a tangent, but addresses are also way more complicated than most people realize - especially if you’re relying on a user to input a correct address or if you need to support multiple countries, somewhere with unique addresses like Queens[0], or you need to differentiate between units of a specific street address that uses something other than unit numbers for a unit designation. At that point you need something like Smarty[1] to validate and parse addresses. [0]: https://stackoverflow.com/questions/2783155/how-to-distinguish-a-ny-queens-style-street-address-from-a-ranged-address-and https://stackoverflow.com/questions/2783155/how-to-distingui... [1]: https://www.smarty.com/ https://www.smarty.com/
- trgn 2y agoFirst the mercator projection, now they're coming after the zip codes.
- serjester 2y agoH3 is awesome here! What I don't think many people realize is that H3 cells and normal geographic data (like zips) are not mutually exclusive. You can take zip outlines, and find all the h3 cells within them and allocate your metric accordingly (population, income, etc). This makes joining disparate data sources quite easy. And this also lets you do all sorts of cool stuff like aggregations, smoothing, flow modeling, etc. We do some geospatial stuff and I wrote a polars plugin to help with this a while back [1]. [1] https://github.com/Filimoa/polars-h3 https://github.com/Filimoa/polars-h3
- hammock 2y agoWhat is the benefit of H3 vs a rectangular grid?
- kylebarron 2y agoEqual distances to each adjacent neighbor: https://www.uber.com/blog/h3/ https://www.uber.com/blog/h3/
- agtech_andy 2y agoZip codes are great for anything with delivery logistics. Anything else is a loose correlation at best, that will likely change over time.
- PLenz 2y agoI gave a talk at DataEngConf many years ago: https://www.datacouncil.ai/talks/zip-codes-and-other-lies-your-map-told-you https://www.datacouncil.ai/talks/zip-codes-and-other-lies-yo...
- zuhayeer 2y agoThis is interesting since zip codes came up in consideration for how we built out our pay choropleth map in the US: https://levels.fyi/heatmap https://levels.fyi/heatmap Though ultimately it was far too granular (for example the Bay Area would be so many different zip codes). Instead we went with Nielsen's DMA (Designated Market Area) mappings within the US to abstract aggregated data a bit better. And of course this DMA dataset also had a different original use case. It was used for TV / media market surveys so it has some weird vestiges. Some regions are grouped very far and wide (you'll notice there's a bit of Denver within Nevada and its just a remnant of how it used to be categorized), but it still provides a bit of a broader level grouping than something acute like zip code. I do like this map from the article though and the granularity you can get with zip code when zooming: https://clausa.app.carto.com/map/29fd0873-64cb-42a6-a90d-c83a8840bbfe?lat=37.176174&lng=-120.862076&zoom=7 https://clausa.app.carto.com/map/29fd0873-64cb-42a6-a90d-c83... We've also been considering using Combined Statistical Areas using population instead. This is something that is under way, and in the interim we've considered charting styles that don't necessarily need borders (for example this bubble map: https://www.levels.fyi/bubble-plot/europe/ https://www.levels.fyi/bubble-plot/europe/). The benefit with DMAs is that it offers full border coverage of the entire US whereas some hubs can still be missing from CSAs if relying on a population threshold. But the plan is to create some of our own regional definitions and borders using our own submissions combined with population. Will be an interesting project. GeoJSON data for the map borders: https://github.com/PublicaMundi/MappingAPI/blob/master/data/geojson/us-states.json https://github.com/PublicaMundi/MappingAPI/blob/master/data/... Nielsen DMA regions: https://blocks.roadtolarissa.com/simzou/6459889 https://blocks.roadtolarissa.com/simzou/6459889
- dhunter_mn 2y agoI used to work for a company that basically merged USPS and Census Bureau data on a monthly basis. The output would be a roadbase that was optimized for address ranges on road segments. ZIP Codes were extra fun to work with.
- eterevsky 2y agoZIP codes are a simple approximation, which does their job good enough in most cases. The alternatives that the author suggests are much more complicated, both in terms of the implementation and in terms of convincing the user to give you their full address.
- ej1 2y ago[flagged]
- dang 2y agoPlease stop. Generated comments are not allowed here.
- Zamicol 2y agoI wrote the blackout system for Comcast TV scheduling. My understanding was that blackouts were used mostly for sports where games need to be available in one area and not others. Contractually, they were required to use zip codes, so I used the US Post office's zip code data to enforce blackouts.
- ej1 2y ago[flagged]
- lacoolj 2y agoFor anyone curious, here is the official US Gov list of ZIP codes in CSV with lots of helpful related data (longitude, latitude, etc.) http://federalgovernmentzipcodes.us/free-zipcode-database-Primary.csv http://federalgovernmentzipcodes.us/free-zipcode-database-Pr...
- yellowbkpk 2y agoThere is no "official US Gov list of ZIP codes". They come from the US Postal Service, and those aren't published for free.
- ivell 2y agoIndia is experimenting with Digipin https://www.indiapost.gov.in/Navigation_Documents/Static_Navigation/DIGIPIN%20Technical%20Document%20Final%20English.pdf https://www.indiapost.gov.in/Navigation_Documents/Static_Nav... Which is derived from longitude and latitude..
- extraduder_ire 2y agoI've seen a few attempts like this, like loc8 and google's plus codes. Is there any advantage to Digipin over existing solutions other than avoiding splitting major cities into very different codes? None stood out to me from that document. The description is written pretty well. Always sad when these schemes don't include a check digit in them though, even if the layout of this one gets typo'd codes pretty close to their intended destination.
- mannyv 2y agoZip codes, zctas, and tiger/line are good enough for what most people need. Maybe you can find an edge by using something more granular...but I'm not sure what edge you'd be looking to get with geodata. Maybe for real estate trends and/or market analysis?
- clutchdude 2y agoI agree. Reading their alternatives, it strikes me with "ZCTA's are the worst form of small area aggregation except for all others." Its not a great geography to use but it is quite useful if you know it's limitations and inaccuracies when you get into it. Stuff like multipolygon entities, island-polys, etc aren't fun to resolve but can be accounted for. Add on that ZCTA's will historically follow some sort of actual boundary(rivers/highways/etc) they can tell a story in a way Census tracts can't.
- honestSysAdmin 2y ago[dead]
- mmmlinux 2y agoCan anyone tell me why I have to enter both my city / state and a zip code. shouldn't one or the other of those plus my street address be enough information?
- ubermonkey 2y agoWeb devs not using a good library that will populate the former from the latter?
- jayknight 2y agoSome libraries will insist that my address is in a different city because my zip code spans the border. I mean if my mail has the other city it still gets to me, but for anything other than mail, they now have the wrong city for me.
- sophacles 2y agoSeveral posts in this thread have linked the recent GCP-gray video on the topic, and it addresses this question better than I can. It's pretty interesting actually
- ubermonkey 2y agoI'm reminded of this: https://www.npr.org/2004/04/01/1805651/post-office-calls-for-portable-vanity-zip-codes https://www.npr.org/2004/04/01/1805651/post-office-calls-for...
- freyfogle 2y agoThere are many problems with zip codes / postal codes but the biggest two we see are: a. Excel treats them as numbers instead of strings of digits and thus drops the leading 0 b. Developers make assumptions about postal codes based on how they work (or more usually how the developer incorrectly thinks they work) in their own country and these assumptions absolutely do NOT hold in other countries. A relevant guide to geocoding and postal codes: https://opencagedata.com/guides/how-to-think-about-postcodes-and-geocoding https://opencagedata.com/guides/how-to-think-about-postcodes...
- paganel 2y agoAlso, "everybody" knows their zip-code/postal-code is mostly an American/British thing, I still remember my British former boss asking me about my zip-code about 20 years ago (I live in Romania, we were implementing the first google-maps-based mashup in this country) and me answering that I have no idea, and that no-one around these parts really knows his/her postal-code. We do know our address, though, or used to, before we had smart-phones.
- gibspaulding 2y ago> Developers make assumptions about postal codes Until very recently I naively assumed that the area of a given zip code would be entirely within the area of some single city or town which would then be entirely within the area of a single county. It was quite a rude awakening working with software that tries to apply the correct local taxes to a given address and finding that the statement “A given X can contain multiple Y” is true for every possible combination of zip, city, and county.
- vikingerik 2y agoThe post office has adapted in turn to that Excel problem. They know it happens. If a parcel has only four digits for the zip code, they'll treat it as a leading zero for routing and delivery.
- freyfogle 2y agoyes, of course. The question is have all the developers writing their own code to deal with zip codes also adapted?
- 0xbadcafebee 2y agoHere's a recent podcast about why ZIP codes are not great for analysis: https://www.npr.org/2025/01/08/1223466587/zip-code-history https://www.npr.org/2025/01/08/1223466587/zip-code-history
- spankalee 2y agoUnironically, what a great sales blog post! It's so well written and informative that I completely didn't mind the "and here's how to do it in Carto" bit in the middle. Instead I thought they earned it.
- Anon84 2y agoThis is an example of the well known Modifiable Areal Unit problem: https://en.wikipedia.org/wiki/Modifiable_areal_unit_problem https://en.wikipedia.org/wiki/Modifiable_areal_unit_problem In general, your statistics depend on how you define your areas and you will get different pictures with different definitions.
- flappyeagle 2y agoNo
- JackFr 2y agoWhen doing your first ML project, zip codes are unsurpassed in providing a set of hand written digits to train on.
- OriPekelman 2y agoWell funny story, some twenty something years ago I actually worked on an election cycle volunteer infra thing in France, and living in Paris which is department 75 and therefore 750xx the prefecture being 75000 I assumed it was neatly hierarchical 75004 won't be far away from 75003 (true)... The French thing being orderly and rational. I didn't need much precision so truncating seemed an easy way to group stuff. Oh the surprise. I never again made such assumptions, let's just say I should have gotten a clue from Corsica being 2A and 2B.
- NelsonMinar 2y agoIt's remarkable how few of the comments posted here are informed by having read the article.
- temporallobe 2y agoI don’t really see the problem but at the same time I understand it’s not a perfect solution. I used to do geospatial work using ESRI products and Zip codes polygons are very useful because people use are often interested in things inside of zip codes especially partial 3-4 digit zip code area, but they are occasionally non-contiguous so you can end up with strange results, visually and mathematically (for example how do you find the “center” of a non-contiguous shape? You don’t). Edit: I wanted to point out that I recall that ESRI maps used to come “out of the box” with zip code polygon layers. While I agree they are technically not polygons in the strictest sense, they often are or they are fully closed shapes or close enough to it - and even if they are missing a few nodes to make a complete polygon, whoever did the digitizing probably manually closed the loop so to speak. Remember, geospatial maps are used for many different purposes, likely none of them having anything to do with postal routes, so in that sense they are “good enough” for most purposes.
- SOLAR_FIELDS 2y agoThere actually are algorithms that compute the centroid of multi part polygons. So you can in fact find the center of a non-contiguous shape. Now, whether that centroid actually has value in a real world application, I’m not sure.
- stevage 2y agoI still miss carto.com (originally CartoDB). It was a really useful platform for uploading spatial data with a decent range of visualisation tools that didn't need code. You could do SQL if you wanted. Then they got rid of the free tier, and set the cheapest tier at (iirc) $150 USD per month. And that was the end of that.
- cwmoore 2y agoNeed a regex[2] using a trie to match valid state-zipcode pairs[1] for webpages likely to contain valid addresses? [1] https://techbio.org/wiki/Addresses/finding-addresses-in-webpages https://techbio.org/wiki/Addresses/finding-addresses-in-webp... [2] https://techbio.org/wiki/Addresses/zipcode-trie-regex https://techbio.org/wiki/Addresses/zipcode-trie-regex
- talkingtab 2y agoThere should be a desensationalizer for titles on HN. When I read this it tricks my brain: Stop using zip codes BANG! Why should I stop using zip codes? Must read!!! And then you go to the old (2019) page, that appears to be filled with useless clicks and arguments that appear biased. "Do not use zip codes for geospatial analysis."
- jwnacnud 2y agoAmen! ZIP Codes (if referring to the US Postal Service) were only ever made for the purpose to sorting and delivering mail more efficiently. ZIP Codes serve the purposes of the US Postal Service, full stop. They don't respect any political or geographical boundaries - and they change at the whim of the USPS, as they were created and are maintained to suit their needs. If used for other purposes they fall short.