-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathseries.py
More file actions
2779 lines (2395 loc) · 100 KB
/
series.py
File metadata and controls
2779 lines (2395 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Series is a 1 dimensional data structure."""
from __future__ import annotations
import datetime
import functools
import itertools
import numbers
import textwrap
import typing
from typing import (
Any,
Callable,
cast,
Iterable,
List,
Literal,
Mapping,
Optional,
overload,
Sequence,
Tuple,
TypeVar,
Union,
)
import warnings
import bigframes_vendored.constants as constants
import bigframes_vendored.pandas.core.series as vendored_pandas_series
import google.cloud.bigquery as bigquery
import numpy
import pandas
from pandas.api import extensions as pd_ext
import pyarrow as pa
import typing_extensions
from bigframes._tools import docs
import bigframes.core
from bigframes.core import agg_expressions, groupby
import bigframes.core.block_transforms as block_ops
import bigframes.core.blocks as blocks
import bigframes.core.expression as ex
import bigframes.core.identifiers as ids
import bigframes.core.indexers
import bigframes.core.indexes as indexes
from bigframes.core.logging import log_adapter
import bigframes.core.ordering as order
import bigframes.core.scalar as scalars
import bigframes.core.utils as utils
import bigframes.core.validations as validations
import bigframes.core.window
from bigframes.core.window import rolling
import bigframes.core.window_spec as windows
import bigframes.dataframe
import bigframes.dtypes
import bigframes.exceptions as bfe
import bigframes.formatting_helpers as formatter
import bigframes.functions
import bigframes.operations as ops
import bigframes.operations.aggregations as agg_ops
import bigframes.operations.blob as blob
import bigframes.operations.lists as lists
import bigframes.operations.plotting as plotting
import bigframes.operations.python_op_maps as python_ops
import bigframes.operations.structs as structs
import bigframes.session
if typing.TYPE_CHECKING:
import bigframes.geopandas.geoseries
import bigframes.operations.datetimes as datetimes
import bigframes.operations.strings as strings
U = TypeVar("U")
LevelType = typing.Union[str, int]
LevelsType = typing.Union[LevelType, typing.Sequence[LevelType]]
_bigquery_function_recommendation_message = (
"Your functions could not be applied directly to the Series."
" Try converting it to a BigFrames BigQuery function."
)
_list = list # Type alias to escape Series.list property
@log_adapter.class_logger
@docs.inherit_docs(vendored_pandas_series.Series)
class Series:
# Must be above 5000 for pandas to delegate to bigframes for binops
__pandas_priority__ = 13000
# Ensure mypy can more robustly determine the type of self._block since it
# gets set in various places.
_block: blocks.Block
def __init__(
self,
data=None,
index=None,
dtype: Optional[bigframes.dtypes.DtypeString | bigframes.dtypes.Dtype] = None,
name: str | None = None,
copy: Optional[bool] = None,
*,
session: Optional[bigframes.session.Session] = None,
):
self._query_job: Optional[bigquery.QueryJob] = None
import bigframes.pandas
# Ignore object dtype if provided, as it provides no additional
# information about what BigQuery type to use.
if dtype is not None and bigframes.dtypes.is_object_like(dtype):
dtype = None
read_pandas_func = (
session.read_pandas
if (session is not None)
else (lambda x: bigframes.pandas.read_pandas(x))
)
block: typing.Optional[blocks.Block] = None
if (name is not None) and not isinstance(name, typing.Hashable):
raise ValueError(
f"BigQuery DataFrames only supports hashable series names. {constants.FEEDBACK_LINK}"
)
if copy is not None and not copy:
raise ValueError(
f"Series constructor only supports copy=True. {constants.FEEDBACK_LINK}"
)
if isinstance(data, blocks.Block):
block = data
elif isinstance(data, bigframes.pandas.Series):
block = data._get_block()
# special case where data is local scalar, but index is bigframes index (maybe very big)
elif (
not utils.is_list_like(data) and not isinstance(data, indexes.Index)
) and isinstance(index, indexes.Index):
block = index._block
block, _ = block.create_constant(data)
block = block.with_column_labels([None])
# prevents no-op reindex later
index = None
elif isinstance(data, indexes.Index) or isinstance(index, indexes.Index):
data = indexes.Index(data, dtype=dtype, name=name, session=session)
# set to none as it has already been applied, avoid re-cast later
if data.nlevels != 1:
raise NotImplementedError("Cannot interpret multi-index as Series.")
# Reset index to promote index columns to value columns, set default index
data_block = data._block.reset_index(drop=False).with_column_labels(
data.names
)
if index is not None: # Align data and index by offset
bf_index = indexes.Index(index, session=session)
idx_block = bf_index._block.reset_index(
drop=False
) # reset to align by offsets, and then reset back
idx_cols = idx_block.value_columns
data_block, (l_mapping, _) = idx_block.join(data_block, how="left")
data_block = data_block.set_index([l_mapping[col] for col in idx_cols])
data_block = data_block.with_index_labels(bf_index.names)
# prevents no-op reindex later
index = None
block = data_block
if block:
assert len(block.value_columns) == 1
assert len(block.column_labels) == 1
if index is not None: # reindexing operation
bf_index = indexes.Index(index)
idx_block = bf_index._block
idx_cols = idx_block.index_columns
block, _ = idx_block.join(block, how="left")
block = block.with_index_labels(bf_index.names)
if name:
block = block.with_column_labels([name])
if dtype:
bf_dtype = bigframes.dtypes.bigframes_type(dtype)
block = block.multi_apply_unary_op(ops.AsTypeOp(to_type=bf_dtype))
else:
if isinstance(dtype, str) and dtype.lower() == "json":
dtype = bigframes.dtypes.JSON_DTYPE
pd_series = pandas.Series(
data=data,
index=index, # type:ignore
dtype=dtype, # type:ignore
name=name,
)
block = read_pandas_func(pd_series)._get_block() # type:ignore
assert block is not None
self._block: blocks.Block = block
self._block.session._register_object(self)
@property
def dt(self) -> datetimes.DatetimeMethods:
import bigframes.operations.datetimes as datetimes
return datetimes.DatetimeMethods(self)
@property
def dtype(self):
bigframes.dtypes.warn_on_db_dtypes_json_dtype([self._dtype])
return self._dtype
@property
def dtypes(self):
bigframes.dtypes.warn_on_db_dtypes_json_dtype([self._dtype])
return self._dtype
@property
def geo(self) -> bigframes.geopandas.geoseries.GeoSeries:
"""
Accessor object for geography properties of the Series values.
Returns:
bigframes.geopandas.geoseries.GeoSeries:
An accessor containing geography methods.
"""
import bigframes.geopandas.geoseries
return bigframes.geopandas.geoseries.GeoSeries(self)
@property
@validations.requires_index
def loc(self) -> bigframes.core.indexers.LocSeriesIndexer:
return bigframes.core.indexers.LocSeriesIndexer(self)
@property
@validations.requires_ordering()
def iloc(self) -> bigframes.core.indexers.IlocSeriesIndexer:
return bigframes.core.indexers.IlocSeriesIndexer(self)
@property
@validations.requires_ordering()
def iat(self) -> bigframes.core.indexers.IatSeriesIndexer:
return bigframes.core.indexers.IatSeriesIndexer(self)
@property
@validations.requires_index
def at(self) -> bigframes.core.indexers.AtSeriesIndexer:
return bigframes.core.indexers.AtSeriesIndexer(self)
@property
def name(self) -> blocks.Label:
return self._name
@name.setter
def name(self, label: blocks.Label):
new_block = self._block.with_column_labels([label])
self._set_block(new_block)
@property
def shape(self) -> typing.Tuple[int]:
return (self._block.shape[0],)
@property
def size(self) -> int:
return self.shape[0]
@property
def ndim(self) -> int:
return 1
@property
def empty(self) -> bool:
return self.shape[0] == 0
@property
def hasnans(self) -> bool:
# Note, hasnans is actually a null check, and NaNs don't count for nullable float
return self.isnull().any()
@property
def values(self) -> numpy.ndarray:
return self.to_numpy()
@property
@validations.requires_index
def index(self) -> indexes.Index:
return indexes.Index.from_frame(self)
@validations.requires_index
def keys(self) -> indexes.Index:
return self.index
@property
def query_job(self) -> Optional[bigquery.QueryJob]:
"""BigQuery job metadata for the most recent query.
Returns:
The most recent `QueryJob
<https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJob>`_.
"""
if self._query_job is None:
self._set_internal_query_job(self._compute_dry_run())
return self._query_job
@property
def struct(self) -> structs.StructAccessor:
return structs.StructAccessor(self)
@property
def list(self) -> lists.ListAccessor:
return lists.ListAccessor(self)
@property
def blob(self) -> blob.BlobAccessor:
"""
Accessor for Blob operations.
"""
warnings.warn(
"The blob accessor is deprecated and will be removed in a future release. Use bigframes.bigquery.obj functions instead.",
category=bfe.ApiDeprecationWarning,
stacklevel=2,
)
return blob.BlobAccessor(self)
@property
@validations.requires_ordering()
def T(self) -> Series:
return self.transpose()
@property
def _info_axis(self) -> indexes.Index:
return self.index
@property
def _session(self) -> bigframes.Session:
return self._get_block().expr.session
@property
def _struct_fields(self) -> List[str]:
if not bigframes.dtypes.is_struct_like(self._dtype):
return []
struct_type = typing.cast(pa.StructType, self._dtype.pyarrow_dtype)
return [struct_type.field(i).name for i in range(struct_type.num_fields)]
@validations.requires_ordering()
def transpose(self) -> Series:
return self
def _set_internal_query_job(self, query_job: Optional[bigquery.QueryJob]):
self._query_job = query_job
def __len__(self):
return self.shape[0]
def __bool__(self):
raise ValueError(
"Cannot convert Series into bool. Consider using .empty(), .item(), .any(), or .all() methods."
)
def __iter__(self) -> typing.Iterator:
return itertools.chain.from_iterable(
map(lambda x: x.squeeze(axis=1), self._block.to_pandas_batches())
)
def __contains__(self, key) -> bool:
return key in self.index
def copy(self) -> Series:
return Series(self._block)
@overload
def rename(
self,
index: Union[blocks.Label, Mapping[Any, Any]] = None,
) -> Series:
...
@overload
def rename(
self,
index: Union[blocks.Label, Mapping[Any, Any]] = None,
*,
inplace: Literal[False],
**kwargs,
) -> Series:
...
@overload
def rename(
self,
index: Union[blocks.Label, Mapping[Any, Any]] = None,
*,
inplace: Literal[True],
**kwargs,
) -> None:
...
def rename(
self,
index: Union[blocks.Label, Mapping[Any, Any]] = None,
*,
inplace: bool = False,
**kwargs,
) -> Optional[Series]:
if len(kwargs) != 0:
raise NotImplementedError(
f"rename does not currently support any keyword arguments. {constants.FEEDBACK_LINK}"
)
# rename the index
if isinstance(index, Mapping):
index = typing.cast(Mapping[Any, Any], index)
block = self._block
for k, v in index.items():
new_idx_ids = []
for idx_id, idx_dtype in zip(block.index_columns, block.index.dtypes):
# Will throw if key type isn't compatible with index type, which leads to invalid SQL.
block.create_constant(k, dtype=idx_dtype)
# Will throw if value type isn't compatible with index type.
block, const_id = block.create_constant(v, dtype=idx_dtype)
block, cond_id = block.project_expr(
ops.ne_op.as_expr(idx_id, ex.const(k))
)
block, new_idx_id = block.apply_ternary_op(
idx_id, cond_id, const_id, ops.where_op
)
new_idx_ids.append(new_idx_id)
block = block.drop_columns([const_id, cond_id])
block = block.set_index(new_idx_ids, index_labels=block.index.names)
if inplace:
self._block = block
return None
else:
return Series(block)
# rename the Series name
if isinstance(index, typing.Hashable):
index = typing.cast(Optional[str], index)
block = self._block.with_column_labels([index])
if inplace:
self._block = block
return None
else:
return Series(block)
raise ValueError(f"Unsupported type of parameter index: {type(index)}")
@overload
def rename_axis(
self,
mapper: typing.Union[blocks.Label, typing.Sequence[blocks.Label]],
) -> Series:
...
@overload
def rename_axis(
self,
mapper: typing.Union[blocks.Label, typing.Sequence[blocks.Label]],
*,
inplace: Literal[False],
**kwargs,
) -> Series:
...
@overload
def rename_axis(
self,
mapper: typing.Union[blocks.Label, typing.Sequence[blocks.Label]],
*,
inplace: Literal[True],
**kwargs,
) -> None:
...
@validations.requires_index
def rename_axis(
self,
mapper: typing.Union[blocks.Label, typing.Sequence[blocks.Label]],
*,
inplace: bool = False,
**kwargs,
) -> Optional[Series]:
if len(kwargs) != 0:
raise NotImplementedError(
f"rename_axis does not currently support any keyword arguments. {constants.FEEDBACK_LINK}"
)
# limited implementation: the new index name is simply the 'mapper' parameter
if _is_list_like(mapper):
labels = mapper
else:
labels = [mapper]
block = self._block.with_index_labels(labels)
if inplace:
self._block = block
return None
else:
return Series(block)
def equals(
self, other: typing.Union[Series, bigframes.dataframe.DataFrame]
) -> bool:
# Must be same object type, same column dtypes, and same label values
if not isinstance(other, Series):
return False
return block_ops.equals(self._block, other._block)
@overload # type: ignore[override]
def reset_index(
self,
level: blocks.LevelsType = ...,
*,
name: typing.Optional[str] = ...,
drop: Literal[False] = ...,
inplace: Literal[False] = ...,
allow_duplicates: Optional[bool] = ...,
) -> bigframes.dataframe.DataFrame:
...
@overload
def reset_index(
self,
level: blocks.LevelsType = ...,
*,
name: typing.Optional[str] = ...,
drop: Literal[True] = ...,
inplace: Literal[False] = ...,
allow_duplicates: Optional[bool] = ...,
) -> Series:
...
@overload
def reset_index(
self,
level: blocks.LevelsType = ...,
*,
name: typing.Optional[str] = ...,
drop: bool = ...,
inplace: Literal[True] = ...,
allow_duplicates: Optional[bool] = ...,
) -> None:
...
@validations.requires_ordering()
def reset_index(
self,
level: blocks.LevelsType = None,
*,
name: typing.Optional[str] = None,
drop: bool = False,
inplace: bool = False,
allow_duplicates: Optional[bool] = None,
) -> bigframes.dataframe.DataFrame | Series | None:
if allow_duplicates is None:
allow_duplicates = False
block = self._block.reset_index(level, drop, allow_duplicates=allow_duplicates)
if drop:
if inplace:
self._set_block(block)
return None
return Series(block)
else:
if inplace:
raise ValueError(
"Series.reset_index cannot combine inplace=True and drop=False"
)
if name:
block = block.assign_label(self._value_column, name)
return bigframes.dataframe.DataFrame(block)
def _repr_mimebundle_(self, include=None, exclude=None):
"""
Custom display method for IPython/Jupyter environments.
This is called by IPython's display system when the object is displayed.
"""
# TODO(b/467647693): Anywidget integration has been tested in Jupyter, VS Code, and
# BQ Studio, but there is a known compatibility issue with Marimo that needs to be addressed.
from bigframes.display import html
return html.repr_mimebundle(self, include=include, exclude=exclude)
def __repr__(self) -> str:
# Protect against errors with uninitialized Series. See:
# https://github.com/googleapis/python-bigquery-dataframes/issues/728
if not hasattr(self, "_block"):
return object.__repr__(self)
# TODO(swast): Add a timeout here? If the query is taking a long time,
# maybe we just print the job metadata that we have so far?
# TODO(swast): Avoid downloading the whole series by using job
# metadata, like we do with DataFrame.
opts = bigframes.options.display
if opts.repr_mode == "deferred":
return formatter.repr_query_job(self._compute_dry_run())
self._cached()
pandas_df, row_count, query_job = self._block.retrieve_repr_request_results(
opts.max_rows
)
self._set_internal_query_job(query_job)
from bigframes.display import plaintext
return plaintext.create_text_representation(
pandas_df,
row_count,
is_series=True,
has_index=len(self._block.index_columns) > 0,
)
def astype(
self,
dtype: Union[bigframes.dtypes.DtypeString, bigframes.dtypes.Dtype],
*,
errors: Literal["raise", "null"] = "raise",
) -> Series:
if errors not in ["raise", "null"]:
raise ValueError("Argument 'errors' must be one of 'raise' or 'null'")
dtype = bigframes.dtypes.bigframes_type(dtype)
return self._apply_unary_op(
bigframes.operations.AsTypeOp(to_type=dtype, safe=(errors == "null"))
)
def to_pandas(
self,
max_download_size: Optional[int] = None,
sampling_method: Optional[str] = None,
random_state: Optional[int] = None,
*,
ordered: bool = True,
dry_run: bool = False,
allow_large_results: Optional[bool] = None,
) -> pandas.Series:
"""Writes Series to pandas Series.
**Examples:**
>>> s = bpd.Series([4, 3, 2])
Download the data from BigQuery and convert it into an in-memory pandas Series.
>>> s.to_pandas()
0 4
1 3
2 2
dtype: Int64
Estimate job statistics without processing or downloading data by using `dry_run=True`.
>>> s.to_pandas(dry_run=True) # doctest: +SKIP
columnCount 1
columnDtypes {None: Int64}
indexLevel 1
indexDtypes [Int64]
projectId bigframes-dev
location US
jobType QUERY
destinationTable {'projectId': 'bigframes-dev', 'datasetId': '_...
useLegacySql False
referencedTables None
totalBytesProcessed 0
cacheHit False
statementType SELECT
creationTime 2025-04-03 18:54:59.219000+00:00
dtype: object
Args:
max_download_size (int, default None):
.. deprecated:: 2.0.0
``max_download_size`` parameter is deprecated. Please use ``to_pandas_batches()``
method instead.
Download size threshold in MB. If ``max_download_size`` is exceeded when downloading data,
the data will be downsampled if ``bigframes.options.sampling.enable_downsampling`` is
``True``, otherwise, an error will be raised. If set to a value other than ``None``,
this will supersede the global config.
sampling_method (str, default None):
.. deprecated:: 2.0.0
``sampling_method`` parameter is deprecated. Please use ``sample()`` method instead.
Downsampling algorithms to be chosen from, the choices are: "head": This algorithm
returns a portion of the data from the beginning. It is fast and requires minimal
computations to perform the downsampling; "uniform": This algorithm returns uniform
random samples of the data. If set to a value other than None, this will supersede
the global config.
random_state (int, default None):
.. deprecated:: 2.0.0
``random_state`` parameter is deprecated. Please use ``sample()`` method instead.
The seed for the uniform downsampling algorithm. If provided, the uniform method may
take longer to execute and require more computation. If set to a value other than
None, this will supersede the global config.
ordered (bool, default True):
Determines whether the resulting pandas series will be ordered.
In some cases, unordered may result in a faster-executing query.
dry_run (bool, default False):
If this argument is true, this method will not process the data. Instead, it returns
a Pandas Series containing dry run job statistics
allow_large_results (bool, default None):
If not None, overrides the global setting to allow or disallow large query results
over the default size limit of 10 GB.
Returns:
pandas.Series: A pandas Series with all rows of this Series if the data_sampling_threshold_mb
is not exceeded; otherwise, a pandas Series with downsampled rows of the DataFrame. If dry_run
is set to True, a pandas Series containing dry run statistics will be returned.
"""
if max_download_size is not None:
msg = bfe.format_message(
"DEPRECATED: The `max_download_size` parameters for `Series.to_pandas()` "
"are deprecated and will be removed soon. Please use `Series.to_pandas_batches()`."
)
warnings.warn(msg, category=FutureWarning)
if sampling_method is not None or random_state is not None:
msg = bfe.format_message(
"DEPRECATED: The `sampling_method` and `random_state` parameters for "
"`Series.to_pandas()` are deprecated and will be removed soon. "
"Please use `Series.sample().to_pandas()` instead for sampling."
)
warnings.warn(msg, category=FutureWarning)
if dry_run:
dry_run_stats, dry_run_job = self._block._compute_dry_run(
max_download_size=max_download_size,
sampling_method=sampling_method,
random_state=random_state,
ordered=ordered,
)
self._set_internal_query_job(dry_run_job)
return dry_run_stats
# Repeat the to_pandas() call to make mypy deduce type correctly, because mypy cannot resolve
# Literal[True/False] to bool
df, query_job = self._block.to_pandas(
max_download_size=max_download_size,
sampling_method=sampling_method,
random_state=random_state,
ordered=ordered,
allow_large_results=allow_large_results,
)
if query_job:
self._set_internal_query_job(query_job)
series = df.squeeze(axis=1)
series.name = self._name
return series
def to_pandas_batches(
self,
page_size: Optional[int] = None,
max_results: Optional[int] = None,
*,
allow_large_results: Optional[bool] = None,
) -> Iterable[pandas.Series]:
"""Stream Series results to an iterable of pandas Series.
page_size and max_results determine the size and number of batches,
see https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJob#google_cloud_bigquery_job_QueryJob_result
**Examples:**
>>> s = bpd.Series([4, 3, 2, 2, 3])
Iterate through the results in batches, limiting the total rows yielded
across all batches via `max_results`:
>>> for s_batch in s.to_pandas_batches(max_results=3):
... print(s_batch)
0 4
1 3
2 2
dtype: Int64
Alternatively, control the approximate size of each batch using `page_size`
and fetch batches manually using `next()`:
>>> it = s.to_pandas_batches(page_size=2)
>>> next(it)
0 4
1 3
dtype: Int64
>>> next(it)
2 2
3 2
dtype: Int64
Args:
page_size (int, default None):
The maximum number of rows of each batch. Non-positive values are ignored.
max_results (int, default None):
The maximum total number of rows of all batches.
allow_large_results (bool, default None):
If not None, overrides the global setting to allow or disallow large query results
over the default size limit of 10 GB.
Returns:
Iterable[pandas.Series]:
An iterable of smaller Series which combine to
form the original Series. Results stream from bigquery,
see https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.table.RowIterator#google_cloud_bigquery_table_RowIterator_to_arrow_iterable
"""
batches = self._block.to_pandas_batches(
page_size=page_size,
max_results=max_results,
allow_large_results=allow_large_results,
)
return map(lambda df: cast(pandas.Series, df.squeeze(1)), batches)
def _compute_dry_run(self) -> bigquery.QueryJob:
_, query_job = self._block._compute_dry_run((self._value_column,))
return query_job
def drop(
self,
labels: typing.Any = None,
*,
axis: typing.Union[int, str] = 0,
index: typing.Any = None,
columns: Union[blocks.Label, typing.Iterable[blocks.Label]] = None,
level: typing.Optional[LevelType] = None,
) -> Series:
if (labels is None) == (index is None):
raise ValueError("Must specify exactly one of 'labels' or 'index'")
if labels is not None:
index = labels
# ignore axis, columns params
block = self._block
level_id = self._resolve_levels(level or 0)[0]
if _is_list_like(index):
block, inverse_condition_id = block.apply_unary_op(
level_id, ops.IsInOp(values=tuple(index), match_nulls=True)
)
block, condition_id = block.apply_unary_op(
inverse_condition_id, ops.invert_op
)
else:
block, condition_id = block.project_expr(
ops.ne_op.as_expr(level_id, ex.const(index))
)
block = block.filter_by_id(condition_id, keep_null=True)
block = block.drop_columns([condition_id])
return Series(block.select_column(self._value_column))
@validations.requires_index
def droplevel(self, level: LevelsType, axis: int | str = 0):
resolved_level_ids = self._resolve_levels(level)
return Series(self._block.drop_levels(resolved_level_ids))
@validations.requires_index
def swaplevel(self, i: int = -2, j: int = -1):
level_i = self._block.index_columns[i]
level_j = self._block.index_columns[j]
mapping = {level_i: level_j, level_j: level_i}
reordering = [
mapping.get(index_id, index_id) for index_id in self._block.index_columns
]
return Series(self._block.reorder_levels(reordering))
@validations.requires_index
def reorder_levels(self, order: LevelsType, axis: int | str = 0):
resolved_level_ids = self._resolve_levels(order)
return Series(self._block.reorder_levels(resolved_level_ids))
def _resolve_levels(self, level: LevelsType) -> typing.Sequence[str]:
return self._block.index.resolve_level(level)
def between(self, left, right, inclusive="both"):
if inclusive not in ["both", "neither", "left", "right"]:
raise ValueError(
"Must set 'inclusive' to one of 'both', 'neither', 'left', or 'right'"
)
left_op = ops.ge_op if (inclusive in ["left", "both"]) else ops.gt_op
right_op = ops.le_op if (inclusive in ["right", "both"]) else ops.lt_op
return self._apply_binary_op(left, left_op).__and__(
self._apply_binary_op(right, right_op)
)
def case_when(self, caselist) -> Series:
cases = []
for condition, output in itertools.chain(caselist, [(True, self)]):
cases.append(condition)
cases.append(output)
# In pandas, the default value if no case matches is the original value.
# This makes it impossible to change the type of the column, but if
# the condition is always True, we know it will match and no subsequent
# conditions matter (including the fallback to `self`). This break allows
# the type to change (see: internal issue 349926559).
if condition is True:
break
return self._apply_nary_op(
ops.case_when_op,
cases,
# Self is already included in "others".
ignore_self=True,
).rename(self.name)
@validations.requires_ordering()
def cumsum(self) -> Series:
return self._apply_window_op(agg_ops.sum_op, windows.cumulative_rows())
@validations.requires_ordering()
def ffill(self, *, limit: typing.Optional[int] = None) -> Series:
window = windows.rows(start=None if limit is None else -limit, end=0)
return self._apply_window_op(agg_ops.LastNonNullOp(), window)
pad = ffill
@validations.requires_ordering()
def bfill(self, *, limit: typing.Optional[int] = None) -> Series:
window = windows.rows(start=0, end=limit)
return self._apply_window_op(agg_ops.FirstNonNullOp(), window)
@validations.requires_ordering()
def cummax(self) -> Series:
return self._apply_window_op(agg_ops.max_op, windows.cumulative_rows())
@validations.requires_ordering()
def cummin(self) -> Series:
return self._apply_window_op(agg_ops.min_op, windows.cumulative_rows())
@validations.requires_ordering()
def cumprod(self) -> Series:
return self._apply_window_op(agg_ops.product_op, windows.cumulative_rows())
@validations.requires_ordering()
def shift(self, periods: int = 1) -> Series:
window_spec = windows.rows()
return self._apply_window_op(agg_ops.ShiftOp(periods), window_spec)
@validations.requires_ordering()
def diff(self, periods: int = 1) -> Series:
window_spec = windows.rows()
return self._apply_window_op(agg_ops.DiffOp(periods), window_spec)
@validations.requires_ordering()
def pct_change(self, periods: int = 1) -> Series:
# Future versions of pandas will not perfrom ffill automatically
series = self.ffill()
return Series(block_ops.pct_change(series._block, periods=periods))
@validations.requires_ordering()
def rank(
self,
axis=0,
method: str = "average",
numeric_only=False,
na_option: str = "keep",
ascending: bool = True,
pct: bool = False,
) -> Series:
return Series(
block_ops.rank(self._block, method, na_option, ascending, pct=pct)
)
def fillna(self, value=None) -> Series:
return self._apply_binary_op(value, ops.fillna_op)
def replace(
self, to_replace: typing.Any, value: typing.Any = None, *, regex: bool = False
):
if regex:
# No-op unless to_replace and series dtype are both string type
if not isinstance(to_replace, str) or not isinstance(
self.dtype, pandas.StringDtype
):
return self
return self._regex_replace(to_replace, value)
elif utils.is_dict_like(to_replace):
return self._mapping_replace(to_replace) # type: ignore
elif utils.is_list_like(to_replace):
replace_list = to_replace
else: # Scalar
replace_list = [to_replace]
replace_list = [
i for i in replace_list if bigframes.dtypes.is_compatible(i, self.dtype)
]
return self._simple_replace(replace_list, value) if replace_list else self
def _regex_replace(self, to_replace: str, value: str):