| 1 |
from io import BytesIO |
| 2 |
import os |
| 3 |
import json |
| 4 |
import pkgutil |
| 5 |
import textwrap |
| 6 |
from typing import Any, Dict, Iterable, List |
| 7 |
from urllib.request import urlopen |
| 8 |
import pandas as pd |
| 9 |
|
| 10 |
# This is the tag in http://github.com/vega/vega-datasets from |
| 11 |
# which the datasets in this repository are sourced. |
| 12 |
SOURCE_TAG = "v1.29.0" |
| 13 |
|
| 14 |
|
| 15 |
def _load_dataset_info() -> Dict[str, Dict[str, Any]]: |
| 16 |
"""This loads dataset info from three package files: |
| 17 |
|
| 18 |
vega_datasets/datasets.json |
| 19 |
vega_datasets/dataset_info.json |
| 20 |
vega_datasets/local_datasets.json |
| 21 |
|
| 22 |
It returns a dictionary with dataset information. |
| 23 |
""" |
| 24 |
|
| 25 |
def load_json(path: str) -> Dict[str, Any]: |
| 26 |
raw = pkgutil.get_data("vega_datasets", path) |
| 27 |
if raw is None: |
| 28 |
raise ValueError("Cannot locate package path vega_datasets:{}".format(path)) |
| 29 |
return json.loads(raw.decode()) |
| 30 |
|
| 31 |
info = load_json("datasets.json") |
| 32 |
descriptions = load_json("dataset_info.json") |
| 33 |
local_datasets = load_json("local_datasets.json") |
| 34 |
|
| 35 |
for name in info: |
| 36 |
info[name]["is_local"] = name in local_datasets |
| 37 |
for name in descriptions: |
| 38 |
info[name].update(descriptions[name]) |
| 39 |
|
| 40 |
return info |
| 41 |
|
| 42 |
|
| 43 |
class Dataset(object): |
| 44 |
"""Class to load a particular dataset by name""" |
| 45 |
|
| 46 |
_instance_doc = """Loader for the {name} dataset. |
| 47 |
|
| 48 |
{data_description} |
| 49 |
|
| 50 |
{bundle_info} |
| 51 |
Dataset source: {url} |
| 52 |
|
| 53 |
Usage |
| 54 |
----- |
| 55 |
|
| 56 |
>>> from vega_datasets import data |
| 57 |
>>> {methodname} = data.{methodname}() |
| 58 |
>>> type({methodname}) |
| 59 |
{return_type} |
| 60 |
|
| 61 |
Equivalently, you can use |
| 62 |
|
| 63 |
>>> {methodname} = data('{name}') |
| 64 |
|
| 65 |
To get the raw dataset rather than the dataframe, use |
| 66 |
|
| 67 |
>>> data_bytes = data.{methodname}.raw() |
| 68 |
>>> type(data_bytes) |
| 69 |
bytes |
| 70 |
|
| 71 |
To find the dataset url, use |
| 72 |
|
| 73 |
>>> data.{methodname}.url |
| 74 |
'{url}' |
| 75 |
{additional_docs} |
| 76 |
Attributes |
| 77 |
---------- |
| 78 |
filename : string |
| 79 |
The filename in which the dataset is stored |
| 80 |
url : string |
| 81 |
The full URL of the dataset at http://vega.github.io |
| 82 |
format : string |
| 83 |
The format of the dataset: usually one of {{'csv', 'tsv', 'json'}} |
| 84 |
pkg_filename : string |
| 85 |
The path to the local dataset within the vega_datasets package |
| 86 |
is_local : bool |
| 87 |
True if the dataset is available locally in the package |
| 88 |
filepath : string |
| 89 |
If is_local is True, the local file path to the dataset. |
| 90 |
|
| 91 |
{reference_info} |
| 92 |
""" |
| 93 |
_additional_docs = "" |
| 94 |
_reference_info = """ |
| 95 |
For information on this dataset, see https://github.com/vega/vega-datasets/ |
| 96 |
""" |
| 97 |
base_url = "https://cdn.jsdelivr.net/npm/vega-datasets@" + SOURCE_TAG + "/data/" |
| 98 |
_dataset_info = _load_dataset_info() |
| 99 |
_pd_read_kwds = {} # type: Dict[str, Any] |
| 100 |
_return_type = pd.DataFrame |
| 101 |
|
| 102 |
@classmethod |
| 103 |
def init(cls, name: str) -> "Dataset": |
| 104 |
"""Return an instance of this class or an appropriate subclass""" |
| 105 |
clsdict = { |
| 106 |
subcls.name: subcls |
| 107 |
for subcls in cls.__subclasses__() |
| 108 |
if hasattr(subcls, "name") |
| 109 |
} |
| 110 |
return clsdict.get(name, cls)(name) |
| 111 |
|
| 112 |
def __init__(self, name: str): |
| 113 |
info = self._infodict(name) |
| 114 |
self.name = name |
| 115 |
self.methodname = name.replace("-", "_") |
| 116 |
self.filename = info["filename"] |
| 117 |
self.url = self.base_url + info["filename"] |
| 118 |
self.format = info["format"] |
| 119 |
self.pkg_filename = "_data/" + self.filename |
| 120 |
self.is_local = info["is_local"] |
| 121 |
self.description = info.get("description", None) |
| 122 |
self.references = info.get("references", None) |
| 123 |
self.__doc__ = self._make_docstring() |
| 124 |
|
| 125 |
def _make_docstring(self) -> str: |
| 126 |
info = self._infodict(self.name) |
| 127 |
|
| 128 |
# construct, indent, and line-wrap dataset description |
| 129 |
description = info.get("description", "") |
| 130 |
if not description: |
| 131 |
description = ( |
| 132 |
"This dataset is described at " "https://github.com/vega/vega-datasets/" |
| 133 |
) |
| 134 |
wrapper = textwrap.TextWrapper( |
| 135 |
width=70, initial_indent="", subsequent_indent=4 * " " |
| 136 |
) |
| 137 |
description = "\n".join(wrapper.wrap(description)) |
| 138 |
|
| 139 |
# construct, indent, and join references |
| 140 |
reflist = info.get("references", []) # type: Iterable[str] |
| 141 |
reflist = (".. [{0}] ".format(i + 1) + ref for i, ref in enumerate(reflist)) |
| 142 |
wrapper = textwrap.TextWrapper( |
| 143 |
width=70, initial_indent=4 * " ", subsequent_indent=7 * " " |
| 144 |
) |
| 145 |
reflist = ("\n".join(wrapper.wrap(ref)) for ref in reflist) |
| 146 |
references = "\n\n".join(reflist) # type: str |
| 147 |
if references.strip(): |
| 148 |
references = "References\n ----------\n" + references |
| 149 |
|
| 150 |
# add information about bundling of data |
| 151 |
if self.is_local: |
| 152 |
bundle_info = ( |
| 153 |
"This dataset is bundled with vega_datasets; " |
| 154 |
"it can be loaded without web access." |
| 155 |
) |
| 156 |
else: |
| 157 |
bundle_info = ( |
| 158 |
"This dataset is not bundled with vega_datasets; " |
| 159 |
"it requires web access to load." |
| 160 |
) |
| 161 |
|
| 162 |
return self._instance_doc.format( |
| 163 |
additional_docs=self._additional_docs, |
| 164 |
data_description=description, |
| 165 |
reference_info=references, |
| 166 |
bundle_info=bundle_info, |
| 167 |
return_type=self._return_type, |
| 168 |
**self.__dict__ |
| 169 |
) |
| 170 |
|
| 171 |
@classmethod |
| 172 |
def list_datasets(cls) -> List[str]: |
| 173 |
"""Return a list of names of available datasets""" |
| 174 |
return sorted(cls._dataset_info.keys()) |
| 175 |
|
| 176 |
@classmethod |
| 177 |
def list_local_datasets(cls) -> List[str]: |
| 178 |
return sorted( |
| 179 |
name for name, info in cls._dataset_info.items() if info["is_local"] |
| 180 |
) |
| 181 |
|
| 182 |
@classmethod |
| 183 |
def _infodict(cls, name: str) -> Dict[str, str]: |
| 184 |
"""load the info dictionary for the given name""" |
| 185 |
info = cls._dataset_info.get(name, None) |
| 186 |
if info is None: |
| 187 |
raise ValueError( |
| 188 |
"No such dataset {0} exists, " |
| 189 |
"use list_datasets() to get a list " |
| 190 |
"of available datasets.".format(name) |
| 191 |
) |
| 192 |
return info |
| 193 |
|
| 194 |
def raw(self, use_local: bool = True) -> bytes: |
| 195 |
"""Load the raw dataset from remote URL or local file |
| 196 |
|
| 197 |
Parameters |
| 198 |
---------- |
| 199 |
use_local : boolean |
| 200 |
If True (default), then attempt to load the dataset locally. If |
| 201 |
False or if the dataset is not available locally, then load the |
| 202 |
data from an external URL. |
| 203 |
""" |
| 204 |
if use_local and self.is_local: |
| 205 |
out = pkgutil.get_data("vega_datasets", self.pkg_filename) |
| 206 |
if out is not None: |
| 207 |
return out |
| 208 |
raise ValueError( |
| 209 |
"Cannot locate package path vega_datasets:{}".format(self.pkg_filename) |
| 210 |
) |
| 211 |
else: |
| 212 |
return urlopen(self.url).read() |
| 213 |
|
| 214 |
def __call__(self, use_local: bool = True, **kwargs) -> pd.DataFrame: |
| 215 |
"""Load and parse the dataset from remote URL or local file |
| 216 |
|
| 217 |
Parameters |
| 218 |
---------- |
| 219 |
use_local : boolean |
| 220 |
If True (default), then attempt to load the dataset locally. If |
| 221 |
False or if the dataset is not available locally, then load the |
| 222 |
data from an external URL. |
| 223 |
**kwargs : |
| 224 |
additional keyword arguments are passed to data parser (usually |
| 225 |
pd.read_csv or pd.read_json, depending on the format of the data |
| 226 |
source) |
| 227 |
|
| 228 |
Returns |
| 229 |
------- |
| 230 |
data : |
| 231 |
parsed data |
| 232 |
""" |
| 233 |
datasource = BytesIO(self.raw(use_local=use_local)) |
| 234 |
|
| 235 |
kwds = self._pd_read_kwds.copy() |
| 236 |
kwds.update(kwargs) |
| 237 |
|
| 238 |
if self.format == "json": |
| 239 |
return pd.read_json(datasource, **kwds) |
| 240 |
elif self.format == "csv": |
| 241 |
return pd.read_csv(datasource, **kwds) |
| 242 |
elif self.format == "tsv": |
| 243 |
kwds.setdefault("sep", "\t") |
| 244 |
return pd.read_csv(datasource, **kwds) |
| 245 |
else: |
| 246 |
raise ValueError( |
| 247 |
"Unrecognized file format: {0}. " |
| 248 |
"Valid options are ['json', 'csv', 'tsv']." |
| 249 |
"".format(self.format) |
| 250 |
) |
| 251 |
|
| 252 |
@property |
| 253 |
def filepath(self) -> str: |
| 254 |
if not self.is_local: |
| 255 |
raise ValueError("filepath is only valid for local datasets") |
| 256 |
else: |
| 257 |
return os.path.abspath( |
| 258 |
os.path.join(os.path.dirname(__file__), "_data", self.filename) |
| 259 |
) |
| 260 |
|
| 261 |
|
| 262 |
class Stocks(Dataset): |
| 263 |
name = "stocks" |
| 264 |
_additional_docs = """ |
| 265 |
For convenience, the stocks dataset supports pivoted output using the |
| 266 |
optional `pivoted` keyword. If pivoted is set to True, each company's |
| 267 |
price history will be returned in a separate column: |
| 268 |
|
| 269 |
>>> df = data.stocks() # not pivoted |
| 270 |
>>> df.head(3) |
| 271 |
symbol date price |
| 272 |
0 MSFT 2000-01-01 39.81 |
| 273 |
1 MSFT 2000-02-01 36.35 |
| 274 |
2 MSFT 2000-03-01 43.22 |
| 275 |
|
| 276 |
>>> df_pivoted = data.stocks(pivoted=True) |
| 277 |
>>> df_pivoted.head() |
| 278 |
symbol AAPL AMZN GOOG IBM MSFT |
| 279 |
date |
| 280 |
2000-01-01 25.94 64.56 NaN 100.52 39.81 |
| 281 |
2000-02-01 28.66 68.87 NaN 92.11 36.35 |
| 282 |
2000-03-01 33.95 67.00 NaN 106.11 43.22 |
| 283 |
""" |
| 284 |
_pd_read_kwds = {"parse_dates": ["date"]} |
| 285 |
|
| 286 |
def __call__(self, pivoted=False, use_local=True, **kwargs): |
| 287 |
"""Load and parse the dataset from remote URL or local file |
| 288 |
|
| 289 |
Parameters |
| 290 |
---------- |
| 291 |
pivoted : boolean, default False |
| 292 |
If True, then pivot data so that each stock is in its own column. |
| 293 |
use_local : boolean |
| 294 |
If True (default), then attempt to load the dataset locally. If |
| 295 |
False or if the dataset is not available locally, then load the |
| 296 |
data from an external URL. |
| 297 |
**kwargs : |
| 298 |
additional keyword arguments are passed to data parser (usually |
| 299 |
pd.read_csv or pd.read_json, depending on the format of the data |
| 300 |
source) |
| 301 |
|
| 302 |
Returns |
| 303 |
------- |
| 304 |
data : DataFrame |
| 305 |
parsed data |
| 306 |
""" |
| 307 |
__doc__ = super(Stocks, self).__call__.__doc__ # noqa:F841 |
| 308 |
data = super(Stocks, self).__call__(use_local=use_local, **kwargs) |
| 309 |
if pivoted: |
| 310 |
data = data.pivot(index="date", columns="symbol", values="price") |
| 311 |
return data |
| 312 |
|
| 313 |
|
| 314 |
class Cars(Dataset): |
| 315 |
name = "cars" |
| 316 |
_pd_read_kwds = {"convert_dates": ["Year"]} |
| 317 |
|
| 318 |
|
| 319 |
class Climate(Dataset): |
| 320 |
name = "climate" |
| 321 |
_pd_read_kwds = {"convert_dates": ["DATE"]} |
| 322 |
|
| 323 |
|
| 324 |
class Github(Dataset): |
| 325 |
name = "github" |
| 326 |
_pd_read_kwds = {"parse_dates": ["time"]} |
| 327 |
|
| 328 |
|
| 329 |
class IowaElectricity(Dataset): |
| 330 |
name = "iowa-electricity" |
| 331 |
_pd_read_kwds = {"parse_dates": ["year"]} |
| 332 |
|
| 333 |
|
| 334 |
class Miserables(Dataset): |
| 335 |
name = "miserables" |
| 336 |
_return_type = tuple |
| 337 |
_additional_docs = """ |
| 338 |
The miserables data contains two dataframes, ``nodes`` and ``links``, |
| 339 |
both of which are returned from this function. |
| 340 |
""" |
| 341 |
|
| 342 |
def __call__(self, use_local=True, **kwargs): |
| 343 |
__doc__ = super(Miserables, self).__call__.__doc__ # noqa:F841 |
| 344 |
dct = json.loads(self.raw(use_local=use_local).decode(), **kwargs) |
| 345 |
nodes = pd.DataFrame.from_records(dct["nodes"], index="index") |
| 346 |
links = pd.DataFrame.from_records(dct["links"]) |
| 347 |
return nodes, links |
| 348 |
|
| 349 |
|
| 350 |
class SeattleTemps(Dataset): |
| 351 |
name = "seattle-temps" |
| 352 |
_pd_read_kwds = {"parse_dates": ["date"]} |
| 353 |
|
| 354 |
|
| 355 |
class SeattleWeather(Dataset): |
| 356 |
name = "seattle-weather" |
| 357 |
_pd_read_kwds = {"parse_dates": ["date"]} |
| 358 |
|
| 359 |
|
| 360 |
class SFTemps(Dataset): |
| 361 |
name = "sf-temps" |
| 362 |
_pd_read_kwds = {"parse_dates": ["date"]} |
| 363 |
|
| 364 |
|
| 365 |
class Sp500(Dataset): |
| 366 |
name = "sp500" |
| 367 |
_pd_read_kwds = {"parse_dates": ["date"]} |
| 368 |
|
| 369 |
|
| 370 |
class UnemploymentAcrossIndustries(Dataset): |
| 371 |
name = "unemployment-across-industries" |
| 372 |
_pd_read_kwds = {"convert_dates": ["date"]} |
| 373 |
|
| 374 |
|
| 375 |
class US_10M(Dataset): |
| 376 |
name = "us-10m" |
| 377 |
_return_type = dict |
| 378 |
_additional_docs = """ |
| 379 |
The us-10m dataset is a TopoJSON file, with a structure that is not |
| 380 |
suitable for storage in a dataframe. For this reason, the loader returns |
| 381 |
a simple Python dictionary. |
| 382 |
""" |
| 383 |
|
| 384 |
def __call__(self, use_local=True, **kwargs): |
| 385 |
__doc__ = super(US_10M, self).__call__.__doc__ # noqa:F841 |
| 386 |
return json.loads(self.raw(use_local=use_local).decode(), **kwargs) |
| 387 |
|
| 388 |
|
| 389 |
class World_110M(Dataset): |
| 390 |
name = "world-110m" |
| 391 |
_return_type = dict |
| 392 |
_additional_docs = """ |
| 393 |
The world-100m dataset is a TopoJSON file, with a structure that is not |
| 394 |
suitable for storage in a dataframe. For this reason, the loader returns |
| 395 |
a simple Python dictionary. |
| 396 |
""" |
| 397 |
|
| 398 |
def __call__(self, use_local=True, **kwargs): |
| 399 |
__doc__ = super(World_110M, self).__call__.__doc__ # noqa:F841 |
| 400 |
return json.loads(self.raw(use_local=use_local).decode(), **kwargs) |
| 401 |
|
| 402 |
|
| 403 |
class ZIPCodes(Dataset): |
| 404 |
name = "zipcodes" |
| 405 |
_pd_read_kwds = {"dtype": {"zip_code": "object"}} |
| 406 |
|
| 407 |
|
| 408 |
class DataLoader(object): |
| 409 |
"""Load a dataset from a local file or remote URL. |
| 410 |
|
| 411 |
There are two ways to call this; for example to load the iris dataset, you |
| 412 |
can call this object and pass the dataset name by string: |
| 413 |
|
| 414 |
>>> from vega_datasets import data |
| 415 |
>>> df = data('iris') |
| 416 |
|
| 417 |
or you can call the associated named method: |
| 418 |
|
| 419 |
>>> df = data.iris() |
| 420 |
|
| 421 |
Optionally, additional parameters can be passed to either of these |
| 422 |
|
| 423 |
Optional parameters |
| 424 |
------------------- |
| 425 |
return_raw : boolean |
| 426 |
If True, then return the raw string or bytes. |
| 427 |
If False (default), then return a pandas dataframe. |
| 428 |
use_local : boolean |
| 429 |
If True (default), then attempt to load the dataset locally. If |
| 430 |
False or if the dataset is not available locally, then load the |
| 431 |
data from an external URL. |
| 432 |
**kwargs : |
| 433 |
additional keyword arguments are passed to the pandas parsing function, |
| 434 |
either ``read_csv()`` or ``read_json()`` depending on the data format. |
| 435 |
""" |
| 436 |
|
| 437 |
_datasets = {name.replace("-", "_"): name for name in Dataset.list_datasets()} |
| 438 |
|
| 439 |
def list_datasets(self): |
| 440 |
return Dataset.list_datasets() |
| 441 |
|
| 442 |
def __call__(self, name, return_raw=False, use_local=True, **kwargs): |
| 443 |
loader = getattr(self, name.replace("-", "_")) |
| 444 |
if return_raw: |
| 445 |
return loader.raw(use_local=use_local, **kwargs) |
| 446 |
else: |
| 447 |
return loader(use_local=use_local, **kwargs) |
| 448 |
|
| 449 |
def __getattr__(self, dataset_name): |
| 450 |
if dataset_name in self._datasets: |
| 451 |
return Dataset.init(self._datasets[dataset_name]) |
| 452 |
else: |
| 453 |
raise AttributeError("No dataset named '{0}'".format(dataset_name)) |
| 454 |
|
| 455 |
def __dir__(self): |
| 456 |
return list(self._datasets.keys()) |
| 457 |
|
| 458 |
|
| 459 |
class LocalDataLoader(DataLoader): |
| 460 |
_datasets = {name.replace("-", "_"): name for name in Dataset.list_local_datasets()} |
| 461 |
|
| 462 |
def list_datasets(self): |
| 463 |
return Dataset.list_local_datasets() |
| 464 |
|
| 465 |
def __getattr__(self, dataset_name): |
| 466 |
if dataset_name in self._datasets: |
| 467 |
return Dataset.init(self._datasets[dataset_name]) |
| 468 |
elif dataset_name in DataLoader._datasets: |
| 469 |
raise ValueError( |
| 470 |
"'{0}' dataset is not available locally. To " |
| 471 |
"download it, use ``vega_datasets.data.{0}()" |
| 472 |
"".format(dataset_name) |
| 473 |
) |
| 474 |
else: |
| 475 |
raise AttributeError("No dataset named '{0}'".format(dataset_name)) |