{"id":14483168,"url":"https://github.com/datagouv/csv-detective","last_synced_at":"2026-04-03T13:04:56.985Z","repository":{"id":38245352,"uuid":"94910602","full_name":"datagouv/csv-detective","owner":"datagouv","description":"CSV inspection","archived":false,"fork":false,"pushed_at":"2025-03-05T13:32:36.000Z","size":2489,"stargazers_count":46,"open_issues_count":6,"forks_count":10,"subscribers_count":11,"default_branch":"master","last_synced_at":"2025-04-07T08:17:22.337Z","etag":null,"topics":["data-analysis","data-engineering","government-data","open-data"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"SGMAP-AGD/csv_detective","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datagouv.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.AGPL.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-06-20T16:07:38.000Z","updated_at":"2025-03-04T10:57:11.000Z","dependencies_parsed_at":"2023-12-19T16:15:40.056Z","dependency_job_id":"e8abc285-3105-4442-a8b7-ff62f4c8bb8a","html_url":"https://github.com/datagouv/csv-detective","commit_stats":null,"previous_names":["etalab/csv_detective","datagouv/csv-detective","etalab/csv-detective"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datagouv%2Fcsv-detective","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datagouv%2Fcsv-detective/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datagouv%2Fcsv-detective/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datagouv%2Fcsv-detective/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datagouv","download_url":"https://codeload.github.com/datagouv/csv-detective/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248404986,"owners_count":21097870,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-analysis","data-engineering","government-data","open-data"],"created_at":"2024-09-03T00:01:34.260Z","updated_at":"2026-04-03T13:04:56.898Z","avatar_url":"https://github.com/datagouv.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# CSV Detective\n\nThis is a package to **automatically detect column content in tabular files**. The script reads either the whole file or the first few rows and performs various checks to see for each column if it matches with various content types. This is currently done through regex and string comparison.\n\nCurrently supported file types: csv, xls, xlsx, ods.\n\nYou can also directly feed the URL of a remote file (from data.gouv.fr for instance).\n\n## How To ?\n\n### Install the package\n\nYou need to have python \u003e= 3.7 installed. We recommend using a virtual environement.\n\n```\npip install csv-detective\n```\n\n### Detect some columns\n\nSay you have a tabular file located at `file_path`. This is how you could use `csv_detective`:\n\n```\n# Import the csv_detective package\nfrom csv_detective import routine\nimport os # for this example only\n\n# Replace by your file path\nfile_path = os.path.join('.', 'tests', 'code_postaux_v201410.csv')\n\n# Open your file and run csv_detective\ninspection_results = routine(\n  file_path, # or file URL\n  num_rows=-1, # Value -1 will analyze all lines of your file, you can change with the number of lines you wish to analyze\n  save_results=False, # Default False. If True, it will save result output into the same directory as the analyzed file, using the same name as your file and .json extension\n  output_profile=True, # Default False. If True, returned dict will contain a property \"profile\" indicating profile (min, max, mean, tops...) of every column of you csv\n  output_schema=True, # Default False. If True, returned dict will contain a property \"schema\" containing basic [tableschema](https://specs.frictionlessdata.io/table-schema/) of your file. This can be use to validate structure of other csv which should match same structure. \n)\n```\n\n## So What Do You Get ?\n\n### Output\n\nThe program creates a `Python` dictionnary with the following information :\n\n```\n{\n    \"encoding\": \"windows-1252\", \t\t\t        # Encoding detected\n    \"separator\": \";\",\t\t\t\t\t\t# Detected CSV separator\n    \"header_row_idx\": 0\t\t\t\t\t# Index of the header (aka how many lines to skip to get it)\n    \"headers\": ['code commune INSEE', 'nom de la commune', 'code postal', \"libellé d'acheminement\"], # Header row\n    \"total_lines\": 42,\t\t\t\t\t# Number of rows (excluding header)\n    \"nb_duplicates\": 0,\t\t\t\t\t# Number of exact duplicates in rows\n    \"heading_columns\": 0,\t\t\t\t\t# Number of heading columns\n    \"trailing_columns\": 0,\t\t\t\t\t# Number of trailing columns\n    \"categorical\": ['Code commune']         # Columns that contain less than 25 different values (arbitrary threshold)\n    \"columns\": { # Property that conciliate detection from labels and content of a column\n        \"Code commune\": {\n            \"python_type\": \"string\",\n            \"format\": \"code_commune_insee\",\n            \"score\": 1.0\n        },\n    },\n    \"columns_labels\": { # Property that return detection from header columns\n        \"Code commune\": {\n            \"python_type\": \"string\",\n            \"format\": \"code_commune_insee\",\n            \"score\": 0.5\n        },\n    },\n    \"columns_fields\": { # Property that return detection from content columns\n        \"Code commune\": {\n            \"python_type\": \"string\",\n            \"format\": \"code_commune_insee\",\n            \"score\": 1.25\n        },\n    },\n    \"profile\": {\n      \"column_name\" : {\n        \"min\": 1, # only int and float\n        \"max: 12, # only int and float\n        \"mean\": 5, # only int and float\n        \"std\": 5, # only int and float\n        \"tops\": [  # 10 most frequent values in the column\n          \"xxx\",\n          \"yyy\",\n          \"...\"\n        ],\n        \"nb_distinct\": 67, # number of distinct values\n        \"nb_missing_values\": 102 # number of empty cells in the column\n      }\n    },\n    \"schema\": { # TableSchema of the file if `output_schema` was set to `True`\n      \"$schema\": \"https://frictionlessdata.io/schemas/table-schema.json\",\n      \"name\": \"\",\n      \"title\": \"\",\n      \"description\": \"\",\n      \"countryCode\": \"FR\",\n      \"homepage\": \"\",\n      \"path\": \"https://github.com/datagouv/csv-detective\",\n      \"resources\": [],\n      \"sources\": [\n        {\"title\": \"Spécification Tableschema\", \"path\": \"https://specs.frictionlessdata.io/table-schema\"},\n        {\"title\": \"schema.data.gouv.fr\", \"path\": \"https://schema.data.gouv.fr\"}\n      ],\n      \"created\": \"2023-02-10\",\n      \"lastModified\": \"2023-02-10\",\n      \"version\": \"0.0.1\",\n      \"contributors\": [\n        {\"title\": \"Table schema bot\", \"email\": \"schema@data.gouv.fr\", \"organisation\": \"data.gouv.fr\", \"role\": \"author\"}\n      ],\n      \"fields\": [\n        {\n          \"name\": \"Code commune\",\n          \"description\": \"Le code INSEE de la commune\",\n          \"example\": \"23150\",\n          \"type\": \"string\",\n          \"formatFR\": \"code_commune_insee\",\n          \"constraints\": {\n            \"required\": False,\n            \"pattern\": \"^([013-9]\\\\d|2[AB1-9])\\\\d{3}$\",\n          }\n        }\n      ]\n    }\n}\n```\n\nThe output slightly differs depending on the file format:\n- csv files have `encoding` and `separator`\n- xls, xls, ods files have `engine` and `sheet_name`\n\n### What Formats Can Be Detected\n\nIncludes :\n\n- Communes, Départements, Régions, Pays\n- Codes Communes, Codes Postaux, Codes Departement, ISO Pays\n- Codes CSP, Description CSP, SIREN\n- E-Mails, URLs, Téléphones FR\n- Years, Dates, Jours de la Semaine FR\n- UUIDs, Mongo ObjectIds\n\n### Format detection and scoring\nFor each column, 3 scores are computed for each format, the higher the score, the more likely the format:\n- the field score based on the values contained in the column (0.0 to 1.0).\n- the label score based on the header of the column (0.0 to 1.0).\n- the overall score, computed as `field_score * (1 + label_score/2)` (0.0 to 1.5).\n\nThe overall score computation aims to give more weight to the column contents while\nstill leveraging the column header.\n\n#### `limited_output` - Select the output mode you want for json report\n\nThis option allows you to select the output mode you want to pass. To do so, you have to pass a `limited_output` argument to the `routine` function. This variable has two possible values:\n\n- `limited_output` defaults to `True` which means report will contain only detected column formats based on a pre-selected threshold proportion in data. Report result is the standard output (an example can be found above in 'Output' section).\nOnly the format with highest score is present in the output.\n- `limited_output=False` means report will contain a full list of all column format possibilities for each input data columns with a value associated which match to the proportion of found column type in data. With this report, user can adjust its rules of detection based on a specific threshold and has a better vision of quality detection for each columns. Results could also be easily transformed into a dataframe (columns types in column / column names in rows) for analysis and test.\n\n## Improvement suggestions\n\n- Smarter refactors\n- Improve performances\n- Test other ways to load and process data (`pandas` alternatives)\n- Add more and more detection modules...\n\nRelated ideas:\n\n- store column names to make a learning model based on column names for (possible pre-screen)\n- normalising data based on column prediction\n- entity resolution (good luck...)\n\n## Why Could This Be of Any Use ?\n\nOrganisations such as [data.gouv.fr](http://data.gouv.fr) aggregate huge amounts of un-normalised data. Performing cross-examination across datasets can be difficult. This tool could help enrich the datasets metadata and facilitate linking them together.\n\n[`udata-hydra`](https://github.com/etalab/udata-hydra) is a crawler that checks, analyzes (using `csv-detective`) and APIfies all tabular files from [data.gouv.fr](http://data.gouv.fr).\n\nAn early version of this analysis of all resources on data.gouv.fr can be found [here](https://github.com/Leobouloc/data.gouv-exploration).\n\n## Release\n\nThe release process uses `bumpr`.\n\n```shell\npip install -r requirements-build.txt\n```\n\n### Process\n\n1. `bumpr` will handle bumping the version according to your command (patch, minor, major)\n2. It will update the CHANGELOG according to the new version being published\n3. It will push a tag with the given version to github\n4. CircleCI will pickup this tag, build the package and publish it to pypi\n5. `bumpr` will have everything ready for the next version (version, changelog...)\n\n### Dry run\n\n```shell\nbumpr -d -v\n```\n\n### Release\n\nThis will release a patch version:\n\n```shell\nbumpr -v\n```\n\nSee bumpr options for minor and major:\n\n```\n$ bumpr -h\nusage: bumpr [-h] [--version] [-v] [-c CONFIG] [-d] [-st] [-b | -pr] [-M] [-m] [-p]\n             [-s SUFFIX] [-u] [-pM] [-pm] [-pp] [-ps PREPARE_SUFFIX] [-pu]\n             [--vcs {git,hg}] [-nc] [-P] [-nP]\n             [file] [files ...]\n\n[...]\n\noptional arguments:\n  -h, --help            show this help message and exit\n  --version             show program's version number and exit\n  -v, --verbose         Verbose output\n  -c CONFIG, --config CONFIG\n                        Specify a configuration file\n  -d, --dryrun          Do not write anything and display a diff\n  -st, --skip-tests     Skip tests\n  -b, --bump            Only perform the bump\n  -pr, --prepare        Only perform the prepare\n\nbump:\n  -M, --major           Bump major version\n  -m, --minor           Bump minor version\n  -p, --patch           Bump patch version\n  -s SUFFIX, --suffix SUFFIX\n                        Set suffix\n  -u, --unsuffix        Unset suffix\n\n[...]\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatagouv%2Fcsv-detective","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatagouv%2Fcsv-detective","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatagouv%2Fcsv-detective/lists"}