Skip to content

interfaces

Report interfaces for analytix.

These are report interfaces equipped with various methods of saving and exporting report data to different formats. They are not designed to be like-for-like mappings of YouTube Analytics API resources.

Currently, there is only one of these interfaces.

Report

An analytics report.

This is an abstraction of the resultTable resource rather than a direct mapping. This class provides additional properties and methods designed to make it easier to perform certain operations.

Changed in version 5.0

This used to be AnalyticsReport.

Parameters:

Name Type Description Default
data Dict[str, Any]

The raw JSON data from the API.

required
type ReportType

The report type.

required

Attributes:

Name Type Description
resource ResultTable

An instance representing a resultTable resource.

type ReportType

The report type.

Source code in analytix/reports/interfaces.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
class Report:
    """An analytics report.

    This is an abstraction of the `resultTable` resource rather than a
    direct mapping. This class provides additional properties and
    methods designed to make it easier to perform certain operations.

    ???+ note "Changed in version 5.0"
        This used to be `AnalyticsReport`.

    Parameters
    ----------
    data
        The raw JSON data from the API.
    type
        The report type.

    Attributes
    ----------
    resource : ResultTable
        An instance representing a `resultTable` resource.
    type : ReportType
        The report type.
    """

    def __init__(self, data: Dict[str, Any], type: "ReportType") -> None:
        self.resource = ResultTable.from_json(data)
        self.type = type
        self._shape = (len(data["rows"]), len(self.resource.column_headers))

    @property
    def shape(self) -> Tuple[int, int]:
        """The shape of the report.

        This is presented in (rows, columns) format.

        Returns
        -------
        Tuple[int, int]
            The shape of the report.

        Examples
        --------
        >>> report.shape
        (120, 42)
        """
        return self._shape

    @property
    def columns(self) -> List[str]:
        """A list of all columns names in the report.

        Returns
        -------
        List[str]
            The column list.

        See Also
        --------
        This does not return a list of column headers. If you want that,
        use `report.resource.column_headers` instead.

        Examples
        --------
        >>> report.columns
        ["day", "subscribedStatus", "views", "likes", "comments"]
        """
        return [c.name for c in self.resource.column_headers]

    @property
    def dimensions(self) -> List[str]:
        """A list of all dimensions in the report.

        Returns
        -------
        List[str]
            The dimension list.

        Examples
        --------
        >>> report.dimensions
        ["day", "subscribedStatus"]
        """
        return [
            c.name
            for c in self.resource.column_headers
            if c.column_type == ColumnType.DIMENSION
        ]

    @property
    def metrics(self) -> List[str]:
        """A list of all metrics in the report.

        Returns
        -------
        List[str]
            The metric list.

        Examples
        --------
        >>> report.metrics
        ["views", "likes", "comments"]
        """
        return [
            c.name
            for c in self.resource.column_headers
            if c.column_type == ColumnType.METRIC
        ]

    def to_json(
        self,
        path: "PathLike",
        *,
        overwrite: bool = False,
        **kwargs: Any,
    ) -> None:
        """Save this report in JSON format.

        This saves the data as it arrived from the YouTube Analytics
        API.

        ???+ note "Changed in version 5.0"
            * `indent` is no longer an argument, but can still be
              provided as part of the `**kwargs`; as such, JSON exports
              are no longer indented by default
            * This will no longer overwrite existing files by default
            * You can now pass additional keyword arguments to be passed
              to the `json.dump` function

        Parameters
        ----------
        path
            The path to save the file to.
        overwrite
            Whether to overwrite an existing file.
        **kwargs
            Additional arguments to pass to `json.dump`. This includes
            `indent`.

        Returns
        -------
        None
            This method doesn't return anything.

        Examples
        --------
        >>> report.to_json("output.json")

        Saving in a pretty format.

        >>> report.to_json("output.json", indent=4)
        """
        path = process_path(path, ".json", overwrite=overwrite)
        data = self.resource.data

        with open(path, "w") as f:
            json.dump(data, f, **kwargs)

        _log.info(f"Saved report as JSON to {path.resolve()}")

    def to_csv(
        self,
        path: "PathLike",
        *,
        delimiter: str = ",",
        overwrite: bool = False,
    ) -> None:
        """Save this report as a CSV or TSV file.

        The filetype is dependent on the delimiter you provide — if you
        pass a tab character as a delimiter, the file will be saved as
        a TSV. It will be saved as a CSV in all other instances.

        ???+ note "Changed in version 5.0"
            This will no longer overwrite existing files by default.

        Parameters
        ----------
        path
            The path to save the file to.
        delimiter
            The character to use as a delimiter. If this is `\\t`, the
            report will be saved as a TSV.
        overwrite
            Whether to overwrite an existing file.

        Returns
        -------
        None
            This method doesn't return anything.

        Examples
        --------
        >>> report.to_csv("output.csv")

        Saving as a TSV.

        >>> report.to_csv("output.tsv", delimiter="\\t")
        """
        extension = ".tsv" if delimiter == "\t" else ".csv"
        path = process_path(path, extension, overwrite=overwrite)

        with open(path, "w") as f:
            f.write(f"{delimiter.join(self.columns)}\n")
            for row in self.resource.rows:
                line = delimiter.join(f"{v}" for v in row)
                f.write(f"{line}\n")

        _log.info(f"Saved report as {extension[1:].upper()} to {path.resolve()}")

    def to_excel(
        self,
        path: "PathLike",
        *,
        sheet_name: str = "Analytics",
        overwrite: bool = False,
    ) -> None:
        """Save this report as an Excel spreadsheet.

        The data cannot be saved to a new sheet in an existing workbook.
        If you wish to do this, you will need to save the data to a new
        spreadsheet file, then copy the data over.

        ???+ note "Changed in version 5.0"
            This will no longer overwrite existing files by default.

        Parameters
        ----------
        path
            The path to save the spreadsheet to.
        sheet_name
            The name to give the sheet the data will be inserted into.
        overwrite
            Whether to overwrite an existing file.

        Returns
        -------
        None
            This method doesn't return anything.

        Notes
        -----
        This requires `openpyxl` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> report.to_excel("output.xlsx")
        """
        if not utils.can_use("openpyxl"):
            raise MissingOptionalComponents("openpyxl")

        from openpyxl import Workbook

        path = process_path(path, ".xlsx", overwrite=overwrite)
        wb = Workbook()
        ws = wb.active
        ws.title = sheet_name

        ws.append(self.columns)
        for row in self.resource.rows:
            ws.append(row)

        wb.save(str(path))
        _log.info(f"Saved report as spreadsheet to {path.resolve()}")

    def to_pandas(self, *, skip_date_conversion: bool = False) -> "pd.DataFrame":
        """Return this report as a pandas DataFrame.

        Parameters
        ----------
        skip_date_conversion
            Whether or not to skip the conversion of "day" and "month"
            columns into a datetime format. If you choose to skip this,
            these columns will be left as strings.

        Returns
        -------
        pandas DataFrame
            A pandas DataFrame.

        Raises
        ------
        MissingOptionalComponents
            pandas is not installed.
        DataFrameConversionError
            There is no data from which to create a DataFrame.

        Notes
        -----
        This requires `pandas` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> df = report.to_pandas()
        >>> df.head(5)
                 day  views  likes  comments  grossRevenue
        0 2022-06-20    778      8         0         2.249
        1 2022-06-21   1062     32         8         3.558
        2 2022-06-22    946     38         6         2.910
        3 2022-06-23   5107    199        15        24.428
        4 2022-06-24   2137     61         2         6.691
        """
        # sourcery skip: class-extract-method
        if not utils.can_use("pandas"):
            raise MissingOptionalComponents("pandas")

        if not self._shape[0]:
            raise DataFrameConversionError(
                "cannot convert to DataFrame as the returned data has no rows",
            )

        import pandas as pd

        df = pd.DataFrame(self.resource.rows, columns=self.columns)

        if not skip_date_conversion and len(s := {"day", "month"} & set(df.columns)):
            col = next(iter(s))
            fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
            df[col] = pd.to_datetime(df[col], format=fmt)
            _log.debug(f"Converted {col!r} column to datetime format")

        return df

    def to_arrow(self, *, skip_date_conversion: bool = False) -> "pa.Table":
        """Export this report as an Apache Arrow table.

        Parameters
        ----------
        skip_date_conversion
            Whether or not to skip the conversion of "day" and "month"
            columns into a datetime format. If you choose to skip this,
            these columns will be left as strings.

        Returns
        -------
        PyArrow Table
            An Apache Arrow table.

        Raises
        ------
        MissingOptionalComponents
            PyArrow is not installed.
        DataFrameConversionError
            There is no data from which to create an Arrow table.

        Notes
        -----
        This requires `pyarrow` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> table = report.to_arrow()
        >>> table.slice(length=3)
        pyarrow.Table
        day: timestamp[ns]
        views: int64
        likes: int64
        comments: int64
        grossRevenue: double
        ----
        day: [[2022-06-20 00:00:00.000000000,...]]
        views: [[778,1062,946,5107,2137]]
        likes: [[8,32,38,199,61]]
        comments: [[0,8,6,15,2]]
        grossRevenue: [[2.249,3.558,2.91,24.428,6.691]]
        """
        if not utils.can_use("pyarrow"):
            raise MissingOptionalComponents("pyarrow")

        if not self._shape[0]:
            raise DataFrameConversionError(
                "cannot convert to Arrow table as the returned data has no rows",
            )

        import pyarrow as pa
        import pyarrow.compute as pc

        table = pa.table(list(zip(*self.resource.rows)), names=self.columns)

        if not skip_date_conversion and len(
            s := {"day", "month"} & set(table.column_names),
        ):
            col = next(iter(s))
            fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
            dt_series = pc.strptime(table.column(col), format=fmt, unit="ns")
            table = table.set_column(0, "day", dt_series)
            _log.debug(f"Converted {col!r} column to datetime format")

        return table

    def to_polars(self, *, skip_date_conversion: bool = False) -> "pl.DataFrame":
        """Return the data as a Polars DataFrame.

        Parameters
        ----------
        skip_date_conversion
            Whether or not to skip the conversion of "day" and "month"
            columns into a date format. If you choose to skip this,
            these columns will be left as strings.

        Returns
        -------
        Polars DataFrame
            A Polars DataFrame.

        Raises
        ------
        MissingOptionalComponents
            Polars is not installed.
        DataFrameConversionError
            There is no data from which to create a DataFrame.

        Notes
        -----
        This requires `polars` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> df = report.to_polars()
        >>> df.head(5)
        shape: (5, 5)
        ┌────────────┬───────┬───────┬──────────┬──────────────┐
        │ day        ┆ views ┆ likes ┆ comments ┆ grossRevenue │
        │ ---        ┆ ---   ┆ ---   ┆ ---      ┆ ---          │
        │ date       ┆ i64   ┆ i64   ┆ i64      ┆ f64          │
        ╞════════════╪═══════╪═══════╪══════════╪══════════════╡
        │ 2022-06-20 ┆ 778   ┆ 8     ┆ 0        ┆ 2.249        │
        ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ 2022-06-21 ┆ 1062  ┆ 32    ┆ 8        ┆ 3.558        │
        ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ 2022-06-22 ┆ 946   ┆ 38    ┆ 6        ┆ 2.91         │
        ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ 2022-06-23 ┆ 5107  ┆ 199   ┆ 15       ┆ 24.428       │
        ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ 2022-06-24 ┆ 2137  ┆ 61    ┆ 2        ┆ 6.691        │
        └────────────┴───────┴───────┴──────────┴──────────────┘
        """
        if not utils.can_use("polars"):
            raise MissingOptionalComponents("polars")

        if not self._shape[0]:
            raise DataFrameConversionError(
                "cannot convert to DataFrame as the returned data has no rows",
            )

        import polars as pl

        df = pl.DataFrame(self.resource.rows, schema=self.columns)

        if not skip_date_conversion and len(s := {"day", "month"} & set(df.columns)):
            col = next(iter(s))
            fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
            df = df.with_columns(pl.col(col).str.strptime(pl.Date, fmt))
            _log.debug(f"Converted {col!r} column to date format")

        return df

    def to_feather(
        self,
        path: "PathLike",
        *,
        skip_date_conversion: bool = False,
        overwrite: bool = False,
        **kwargs: Any,
    ) -> None:
        """Save this report as an Apache Feather file.

        ???+ note "Changed in version 5.0"
            * This will no longer overwrite existing files by default
            * You can now pass additional keyword arguments to be passed
              to the `pf.write_feather` function
            * This no longer returns a PyArrow table

        Parameters
        ----------
        path
            The path to save the file to.
        skip_date_conversion
            Whether or not to skip the conversion of "day" and "month"
            columns into a datetime format. If you choose to skip this,
            these columns will be left as strings.
        overwrite
            Whether to overwrite an existing file.

        Returns
        -------
        None
            This method doesn't return anything.

        Other Parameters
        ----------------
        **kwargs
            Additional arguments to pass to `pf.write_feather`.

        Notes
        -----
        This requires `pyarrow` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> report.to_feather("output.feather")
        """
        if not utils.can_use("pyarrow"):
            raise MissingOptionalComponents("pyarrow")

        import pyarrow.feather as pf

        path = process_path(path, ".feather", overwrite=overwrite)
        pf.write_feather(
            self.to_arrow(skip_date_conversion=skip_date_conversion),
            path,
            **kwargs,
        )

        _log.info(f"Saved report as Apache Feather file to {path.resolve()}")

    def to_parquet(
        self,
        path: "PathLike",
        *,
        skip_date_conversion: bool = False,
        overwrite: bool = False,
        **kwargs: Any,
    ) -> None:
        """Save this report as an Apache Parquet file.

        ???+ note "Changed in version 5.0"
            * This will no longer overwrite existing files by default
            * You can now pass additional keyword arguments to be passed
              to the `pq.write_table` function
            * This no longer returns a PyArrow table

        Parameters
        ----------
        path
            The path to save the file to.
        skip_date_conversion
            Whether or not to skip the conversion of "day" and "month"
            columns into a datetime format. If you choose to skip this,
            these columns will be left as strings.
        overwrite
            Whether to overwrite an existing file.

        Returns
        -------
        None
            This method doesn't return anything.

        Other Parameters
        ----------------
        **kwargs
            Additional arguments to pass to `pq.write_table`.

        Notes
        -----
        This requires `pyarrow` to be installed to use, which is an
        optional dependency.

        Examples
        --------
        >>> report.to_parquet("output.parquet")
        """

        if not utils.can_use("pyarrow"):
            raise MissingOptionalComponents("pyarrow")

        import pyarrow.parquet as pq

        path = process_path(path, ".parquet", overwrite=overwrite)
        pq.write_table(
            self.to_arrow(skip_date_conversion=skip_date_conversion),
            path,
            **kwargs,
        )

        _log.info(f"Saved report as Apache Parquet file to {path.resolve()}")

columns property

columns: List[str]

A list of all columns names in the report.

Returns:

Type Description
List[str]

The column list.

See Also

This does not return a list of column headers. If you want that, use report.resource.column_headers instead.

Examples:

>>> report.columns
["day", "subscribedStatus", "views", "likes", "comments"]

dimensions property

dimensions: List[str]

A list of all dimensions in the report.

Returns:

Type Description
List[str]

The dimension list.

Examples:

>>> report.dimensions
["day", "subscribedStatus"]

metrics property

metrics: List[str]

A list of all metrics in the report.

Returns:

Type Description
List[str]

The metric list.

Examples:

>>> report.metrics
["views", "likes", "comments"]

shape property

shape: Tuple[int, int]

The shape of the report.

This is presented in (rows, columns) format.

Returns:

Type Description
Tuple[int, int]

The shape of the report.

Examples:

>>> report.shape
(120, 42)

to_arrow

to_arrow(*, skip_date_conversion: bool = False) -> pa.Table

Export this report as an Apache Arrow table.

Parameters:

Name Type Description Default
skip_date_conversion bool

Whether or not to skip the conversion of "day" and "month" columns into a datetime format. If you choose to skip this, these columns will be left as strings.

False

Returns:

Type Description
PyArrow Table

An Apache Arrow table.

Raises:

Type Description
MissingOptionalComponents

PyArrow is not installed.

DataFrameConversionError

There is no data from which to create an Arrow table.

Notes

This requires pyarrow to be installed to use, which is an optional dependency.

Examples:

>>> table = report.to_arrow()
>>> table.slice(length=3)
pyarrow.Table
day: timestamp[ns]
views: int64
likes: int64
comments: int64
grossRevenue: double
----
day: [[2022-06-20 00:00:00.000000000,...]]
views: [[778,1062,946,5107,2137]]
likes: [[8,32,38,199,61]]
comments: [[0,8,6,15,2]]
grossRevenue: [[2.249,3.558,2.91,24.428,6.691]]
Source code in analytix/reports/interfaces.py
def to_arrow(self, *, skip_date_conversion: bool = False) -> "pa.Table":
    """Export this report as an Apache Arrow table.

    Parameters
    ----------
    skip_date_conversion
        Whether or not to skip the conversion of "day" and "month"
        columns into a datetime format. If you choose to skip this,
        these columns will be left as strings.

    Returns
    -------
    PyArrow Table
        An Apache Arrow table.

    Raises
    ------
    MissingOptionalComponents
        PyArrow is not installed.
    DataFrameConversionError
        There is no data from which to create an Arrow table.

    Notes
    -----
    This requires `pyarrow` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> table = report.to_arrow()
    >>> table.slice(length=3)
    pyarrow.Table
    day: timestamp[ns]
    views: int64
    likes: int64
    comments: int64
    grossRevenue: double
    ----
    day: [[2022-06-20 00:00:00.000000000,...]]
    views: [[778,1062,946,5107,2137]]
    likes: [[8,32,38,199,61]]
    comments: [[0,8,6,15,2]]
    grossRevenue: [[2.249,3.558,2.91,24.428,6.691]]
    """
    if not utils.can_use("pyarrow"):
        raise MissingOptionalComponents("pyarrow")

    if not self._shape[0]:
        raise DataFrameConversionError(
            "cannot convert to Arrow table as the returned data has no rows",
        )

    import pyarrow as pa
    import pyarrow.compute as pc

    table = pa.table(list(zip(*self.resource.rows)), names=self.columns)

    if not skip_date_conversion and len(
        s := {"day", "month"} & set(table.column_names),
    ):
        col = next(iter(s))
        fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
        dt_series = pc.strptime(table.column(col), format=fmt, unit="ns")
        table = table.set_column(0, "day", dt_series)
        _log.debug(f"Converted {col!r} column to datetime format")

    return table

to_csv

to_csv(path: PathLike, *, delimiter: str = ',', overwrite: bool = False) -> None

Save this report as a CSV or TSV file.

The filetype is dependent on the delimiter you provide — if you pass a tab character as a delimiter, the file will be saved as a TSV. It will be saved as a CSV in all other instances.

Changed in version 5.0

This will no longer overwrite existing files by default.

Parameters:

Name Type Description Default
path PathLike

The path to save the file to.

required
delimiter str

The character to use as a delimiter. If this is \t, the report will be saved as a TSV.

','
overwrite bool

Whether to overwrite an existing file.

False

Returns:

Type Description
None

This method doesn't return anything.

Examples:

>>> report.to_csv("output.csv")

Saving as a TSV.

>>> report.to_csv("output.tsv", delimiter="\t")
Source code in analytix/reports/interfaces.py
def to_csv(
    self,
    path: "PathLike",
    *,
    delimiter: str = ",",
    overwrite: bool = False,
) -> None:
    """Save this report as a CSV or TSV file.

    The filetype is dependent on the delimiter you provide — if you
    pass a tab character as a delimiter, the file will be saved as
    a TSV. It will be saved as a CSV in all other instances.

    ???+ note "Changed in version 5.0"
        This will no longer overwrite existing files by default.

    Parameters
    ----------
    path
        The path to save the file to.
    delimiter
        The character to use as a delimiter. If this is `\\t`, the
        report will be saved as a TSV.
    overwrite
        Whether to overwrite an existing file.

    Returns
    -------
    None
        This method doesn't return anything.

    Examples
    --------
    >>> report.to_csv("output.csv")

    Saving as a TSV.

    >>> report.to_csv("output.tsv", delimiter="\\t")
    """
    extension = ".tsv" if delimiter == "\t" else ".csv"
    path = process_path(path, extension, overwrite=overwrite)

    with open(path, "w") as f:
        f.write(f"{delimiter.join(self.columns)}\n")
        for row in self.resource.rows:
            line = delimiter.join(f"{v}" for v in row)
            f.write(f"{line}\n")

    _log.info(f"Saved report as {extension[1:].upper()} to {path.resolve()}")

to_excel

to_excel(path: PathLike, *, sheet_name: str = 'Analytics', overwrite: bool = False) -> None

Save this report as an Excel spreadsheet.

The data cannot be saved to a new sheet in an existing workbook. If you wish to do this, you will need to save the data to a new spreadsheet file, then copy the data over.

Changed in version 5.0

This will no longer overwrite existing files by default.

Parameters:

Name Type Description Default
path PathLike

The path to save the spreadsheet to.

required
sheet_name str

The name to give the sheet the data will be inserted into.

'Analytics'
overwrite bool

Whether to overwrite an existing file.

False

Returns:

Type Description
None

This method doesn't return anything.

Notes

This requires openpyxl to be installed to use, which is an optional dependency.

Examples:

>>> report.to_excel("output.xlsx")
Source code in analytix/reports/interfaces.py
def to_excel(
    self,
    path: "PathLike",
    *,
    sheet_name: str = "Analytics",
    overwrite: bool = False,
) -> None:
    """Save this report as an Excel spreadsheet.

    The data cannot be saved to a new sheet in an existing workbook.
    If you wish to do this, you will need to save the data to a new
    spreadsheet file, then copy the data over.

    ???+ note "Changed in version 5.0"
        This will no longer overwrite existing files by default.

    Parameters
    ----------
    path
        The path to save the spreadsheet to.
    sheet_name
        The name to give the sheet the data will be inserted into.
    overwrite
        Whether to overwrite an existing file.

    Returns
    -------
    None
        This method doesn't return anything.

    Notes
    -----
    This requires `openpyxl` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> report.to_excel("output.xlsx")
    """
    if not utils.can_use("openpyxl"):
        raise MissingOptionalComponents("openpyxl")

    from openpyxl import Workbook

    path = process_path(path, ".xlsx", overwrite=overwrite)
    wb = Workbook()
    ws = wb.active
    ws.title = sheet_name

    ws.append(self.columns)
    for row in self.resource.rows:
        ws.append(row)

    wb.save(str(path))
    _log.info(f"Saved report as spreadsheet to {path.resolve()}")

to_feather

to_feather(path: PathLike, *, skip_date_conversion: bool = False, overwrite: bool = False, **kwargs: Any) -> None

Save this report as an Apache Feather file.

Changed in version 5.0
  • This will no longer overwrite existing files by default
  • You can now pass additional keyword arguments to be passed to the pf.write_feather function
  • This no longer returns a PyArrow table

Parameters:

Name Type Description Default
path PathLike

The path to save the file to.

required
skip_date_conversion bool

Whether or not to skip the conversion of "day" and "month" columns into a datetime format. If you choose to skip this, these columns will be left as strings.

False
overwrite bool

Whether to overwrite an existing file.

False

Returns:

Type Description
None

This method doesn't return anything.

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to pass to pf.write_feather.

Notes

This requires pyarrow to be installed to use, which is an optional dependency.

Examples:

>>> report.to_feather("output.feather")
Source code in analytix/reports/interfaces.py
def to_feather(
    self,
    path: "PathLike",
    *,
    skip_date_conversion: bool = False,
    overwrite: bool = False,
    **kwargs: Any,
) -> None:
    """Save this report as an Apache Feather file.

    ???+ note "Changed in version 5.0"
        * This will no longer overwrite existing files by default
        * You can now pass additional keyword arguments to be passed
          to the `pf.write_feather` function
        * This no longer returns a PyArrow table

    Parameters
    ----------
    path
        The path to save the file to.
    skip_date_conversion
        Whether or not to skip the conversion of "day" and "month"
        columns into a datetime format. If you choose to skip this,
        these columns will be left as strings.
    overwrite
        Whether to overwrite an existing file.

    Returns
    -------
    None
        This method doesn't return anything.

    Other Parameters
    ----------------
    **kwargs
        Additional arguments to pass to `pf.write_feather`.

    Notes
    -----
    This requires `pyarrow` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> report.to_feather("output.feather")
    """
    if not utils.can_use("pyarrow"):
        raise MissingOptionalComponents("pyarrow")

    import pyarrow.feather as pf

    path = process_path(path, ".feather", overwrite=overwrite)
    pf.write_feather(
        self.to_arrow(skip_date_conversion=skip_date_conversion),
        path,
        **kwargs,
    )

    _log.info(f"Saved report as Apache Feather file to {path.resolve()}")

to_json

to_json(path: PathLike, *, overwrite: bool = False, **kwargs: Any) -> None

Save this report in JSON format.

This saves the data as it arrived from the YouTube Analytics API.

Changed in version 5.0
  • indent is no longer an argument, but can still be provided as part of the **kwargs; as such, JSON exports are no longer indented by default
  • This will no longer overwrite existing files by default
  • You can now pass additional keyword arguments to be passed to the json.dump function

Parameters:

Name Type Description Default
path PathLike

The path to save the file to.

required
overwrite bool

Whether to overwrite an existing file.

False
**kwargs Any

Additional arguments to pass to json.dump. This includes indent.

{}

Returns:

Type Description
None

This method doesn't return anything.

Examples:

>>> report.to_json("output.json")

Saving in a pretty format.

>>> report.to_json("output.json", indent=4)
Source code in analytix/reports/interfaces.py
def to_json(
    self,
    path: "PathLike",
    *,
    overwrite: bool = False,
    **kwargs: Any,
) -> None:
    """Save this report in JSON format.

    This saves the data as it arrived from the YouTube Analytics
    API.

    ???+ note "Changed in version 5.0"
        * `indent` is no longer an argument, but can still be
          provided as part of the `**kwargs`; as such, JSON exports
          are no longer indented by default
        * This will no longer overwrite existing files by default
        * You can now pass additional keyword arguments to be passed
          to the `json.dump` function

    Parameters
    ----------
    path
        The path to save the file to.
    overwrite
        Whether to overwrite an existing file.
    **kwargs
        Additional arguments to pass to `json.dump`. This includes
        `indent`.

    Returns
    -------
    None
        This method doesn't return anything.

    Examples
    --------
    >>> report.to_json("output.json")

    Saving in a pretty format.

    >>> report.to_json("output.json", indent=4)
    """
    path = process_path(path, ".json", overwrite=overwrite)
    data = self.resource.data

    with open(path, "w") as f:
        json.dump(data, f, **kwargs)

    _log.info(f"Saved report as JSON to {path.resolve()}")

to_pandas

to_pandas(*, skip_date_conversion: bool = False) -> pd.DataFrame

Return this report as a pandas DataFrame.

Parameters:

Name Type Description Default
skip_date_conversion bool

Whether or not to skip the conversion of "day" and "month" columns into a datetime format. If you choose to skip this, these columns will be left as strings.

False

Returns:

Type Description
pandas DataFrame

A pandas DataFrame.

Raises:

Type Description
MissingOptionalComponents

pandas is not installed.

DataFrameConversionError

There is no data from which to create a DataFrame.

Notes

This requires pandas to be installed to use, which is an optional dependency.

Examples:

>>> df = report.to_pandas()
>>> df.head(5)
         day  views  likes  comments  grossRevenue
0 2022-06-20    778      8         0         2.249
1 2022-06-21   1062     32         8         3.558
2 2022-06-22    946     38         6         2.910
3 2022-06-23   5107    199        15        24.428
4 2022-06-24   2137     61         2         6.691
Source code in analytix/reports/interfaces.py
def to_pandas(self, *, skip_date_conversion: bool = False) -> "pd.DataFrame":
    """Return this report as a pandas DataFrame.

    Parameters
    ----------
    skip_date_conversion
        Whether or not to skip the conversion of "day" and "month"
        columns into a datetime format. If you choose to skip this,
        these columns will be left as strings.

    Returns
    -------
    pandas DataFrame
        A pandas DataFrame.

    Raises
    ------
    MissingOptionalComponents
        pandas is not installed.
    DataFrameConversionError
        There is no data from which to create a DataFrame.

    Notes
    -----
    This requires `pandas` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> df = report.to_pandas()
    >>> df.head(5)
             day  views  likes  comments  grossRevenue
    0 2022-06-20    778      8         0         2.249
    1 2022-06-21   1062     32         8         3.558
    2 2022-06-22    946     38         6         2.910
    3 2022-06-23   5107    199        15        24.428
    4 2022-06-24   2137     61         2         6.691
    """
    # sourcery skip: class-extract-method
    if not utils.can_use("pandas"):
        raise MissingOptionalComponents("pandas")

    if not self._shape[0]:
        raise DataFrameConversionError(
            "cannot convert to DataFrame as the returned data has no rows",
        )

    import pandas as pd

    df = pd.DataFrame(self.resource.rows, columns=self.columns)

    if not skip_date_conversion and len(s := {"day", "month"} & set(df.columns)):
        col = next(iter(s))
        fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
        df[col] = pd.to_datetime(df[col], format=fmt)
        _log.debug(f"Converted {col!r} column to datetime format")

    return df

to_parquet

to_parquet(path: PathLike, *, skip_date_conversion: bool = False, overwrite: bool = False, **kwargs: Any) -> None

Save this report as an Apache Parquet file.

Changed in version 5.0
  • This will no longer overwrite existing files by default
  • You can now pass additional keyword arguments to be passed to the pq.write_table function
  • This no longer returns a PyArrow table

Parameters:

Name Type Description Default
path PathLike

The path to save the file to.

required
skip_date_conversion bool

Whether or not to skip the conversion of "day" and "month" columns into a datetime format. If you choose to skip this, these columns will be left as strings.

False
overwrite bool

Whether to overwrite an existing file.

False

Returns:

Type Description
None

This method doesn't return anything.

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to pass to pq.write_table.

Notes

This requires pyarrow to be installed to use, which is an optional dependency.

Examples:

>>> report.to_parquet("output.parquet")
Source code in analytix/reports/interfaces.py
def to_parquet(
    self,
    path: "PathLike",
    *,
    skip_date_conversion: bool = False,
    overwrite: bool = False,
    **kwargs: Any,
) -> None:
    """Save this report as an Apache Parquet file.

    ???+ note "Changed in version 5.0"
        * This will no longer overwrite existing files by default
        * You can now pass additional keyword arguments to be passed
          to the `pq.write_table` function
        * This no longer returns a PyArrow table

    Parameters
    ----------
    path
        The path to save the file to.
    skip_date_conversion
        Whether or not to skip the conversion of "day" and "month"
        columns into a datetime format. If you choose to skip this,
        these columns will be left as strings.
    overwrite
        Whether to overwrite an existing file.

    Returns
    -------
    None
        This method doesn't return anything.

    Other Parameters
    ----------------
    **kwargs
        Additional arguments to pass to `pq.write_table`.

    Notes
    -----
    This requires `pyarrow` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> report.to_parquet("output.parquet")
    """

    if not utils.can_use("pyarrow"):
        raise MissingOptionalComponents("pyarrow")

    import pyarrow.parquet as pq

    path = process_path(path, ".parquet", overwrite=overwrite)
    pq.write_table(
        self.to_arrow(skip_date_conversion=skip_date_conversion),
        path,
        **kwargs,
    )

    _log.info(f"Saved report as Apache Parquet file to {path.resolve()}")

to_polars

to_polars(*, skip_date_conversion: bool = False) -> pl.DataFrame

Return the data as a Polars DataFrame.

Parameters:

Name Type Description Default
skip_date_conversion bool

Whether or not to skip the conversion of "day" and "month" columns into a date format. If you choose to skip this, these columns will be left as strings.

False

Returns:

Type Description
Polars DataFrame

A Polars DataFrame.

Raises:

Type Description
MissingOptionalComponents

Polars is not installed.

DataFrameConversionError

There is no data from which to create a DataFrame.

Notes

This requires polars to be installed to use, which is an optional dependency.

Examples:

>>> df = report.to_polars()
>>> df.head(5)
shape: (5, 5)
┌────────────┬───────┬───────┬──────────┬──────────────┐
│ day        ┆ views ┆ likes ┆ comments ┆ grossRevenue │
│ ---        ┆ ---   ┆ ---   ┆ ---      ┆ ---          │
│ date       ┆ i64   ┆ i64   ┆ i64      ┆ f64          │
╞════════════╪═══════╪═══════╪══════════╪══════════════╡
│ 2022-06-20 ┆ 778   ┆ 8     ┆ 0        ┆ 2.249        │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-06-21 ┆ 1062  ┆ 32    ┆ 8        ┆ 3.558        │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-06-22 ┆ 946   ┆ 38    ┆ 6        ┆ 2.91         │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-06-23 ┆ 5107  ┆ 199   ┆ 15       ┆ 24.428       │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-06-24 ┆ 2137  ┆ 61    ┆ 2        ┆ 6.691        │
└────────────┴───────┴───────┴──────────┴──────────────┘
Source code in analytix/reports/interfaces.py
def to_polars(self, *, skip_date_conversion: bool = False) -> "pl.DataFrame":
    """Return the data as a Polars DataFrame.

    Parameters
    ----------
    skip_date_conversion
        Whether or not to skip the conversion of "day" and "month"
        columns into a date format. If you choose to skip this,
        these columns will be left as strings.

    Returns
    -------
    Polars DataFrame
        A Polars DataFrame.

    Raises
    ------
    MissingOptionalComponents
        Polars is not installed.
    DataFrameConversionError
        There is no data from which to create a DataFrame.

    Notes
    -----
    This requires `polars` to be installed to use, which is an
    optional dependency.

    Examples
    --------
    >>> df = report.to_polars()
    >>> df.head(5)
    shape: (5, 5)
    ┌────────────┬───────┬───────┬──────────┬──────────────┐
    │ day        ┆ views ┆ likes ┆ comments ┆ grossRevenue │
    │ ---        ┆ ---   ┆ ---   ┆ ---      ┆ ---          │
    │ date       ┆ i64   ┆ i64   ┆ i64      ┆ f64          │
    ╞════════════╪═══════╪═══════╪══════════╪══════════════╡
    │ 2022-06-20 ┆ 778   ┆ 8     ┆ 0        ┆ 2.249        │
    ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 2022-06-21 ┆ 1062  ┆ 32    ┆ 8        ┆ 3.558        │
    ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 2022-06-22 ┆ 946   ┆ 38    ┆ 6        ┆ 2.91         │
    ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 2022-06-23 ┆ 5107  ┆ 199   ┆ 15       ┆ 24.428       │
    ├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 2022-06-24 ┆ 2137  ┆ 61    ┆ 2        ┆ 6.691        │
    └────────────┴───────┴───────┴──────────┴──────────────┘
    """
    if not utils.can_use("polars"):
        raise MissingOptionalComponents("polars")

    if not self._shape[0]:
        raise DataFrameConversionError(
            "cannot convert to DataFrame as the returned data has no rows",
        )

    import polars as pl

    df = pl.DataFrame(self.resource.rows, schema=self.columns)

    if not skip_date_conversion and len(s := {"day", "month"} & set(df.columns)):
        col = next(iter(s))
        fmt = {"day": "%Y-%m-%d", "month": "%Y-%m"}[col]
        df = df.with_columns(pl.col(col).str.strptime(pl.Date, fmt))
        _log.debug(f"Converted {col!r} column to date format")

    return df