# 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.
"""DataFrame is a two dimensional data structure."""
from __future__ import annotations
import datetime
import inspect
import itertools
import re
import sys
import textwrap
import typing
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Hashable,
Iterable,
List,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import bigframes_vendored.constants as constants
import bigframes_vendored.pandas.core.frame as vendored_pandas_frame
import bigframes_vendored.pandas.pandas._typing as vendored_pandas_typing
import google.api_core.exceptions
import google.cloud.bigquery as bigquery
import google.cloud.bigquery.job
import google.cloud.bigquery.table
import numpy
import pandas
import pyarrow
import tabulate
from pandas.api import extensions as pd_ext
import bigframes.constants
import bigframes.core
import bigframes.core.block_transforms as block_ops
import bigframes.core.blocks as blocks
import bigframes.core.col
import bigframes.core.convert
import bigframes.core.explode
import bigframes.core.expression as ex
import bigframes.core.groupby as groupby
import bigframes.core.guid
import bigframes.core.indexers as indexers
import bigframes.core.indexes as indexes
import bigframes.core.interchange
import bigframes.core.ordering as order
import bigframes.core.utils as utils
import bigframes.core.validations as validations
import bigframes.core.window
import bigframes.core.window_spec as windows
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.plotting as plotting
import bigframes.operations.structs
import bigframes.series
import bigframes.session._io.bigquery
import bigframes.session.execution_spec as ex_spec
from bigframes._tools import docs
from bigframes.core import agg_expressions
from bigframes.core.logging import log_adapter
from bigframes.core.window import rolling
from bigframes.functions import function_typing
if TYPE_CHECKING:
from _typeshed import SupportsRichComparison
import bigframes.extensions.bigframes.dataframe_accessor as bigquery_accessor
import bigframes.session
SingleItemValue = Union[
bigframes.series.Series,
int,
float,
str,
pandas.Timedelta,
Callable,
bigframes.core.col.Expression,
]
MultiItemValue = Union[
"DataFrame", Sequence[int | float | str | pandas.Timedelta | Callable]
]
U = TypeVar("U")
LevelType = typing.Hashable
LevelsType = typing.Union[LevelType, typing.Sequence[LevelType]]
ERROR_IO_ONLY_GS_PATHS = f"Only Google Cloud Storage (gs://...) paths are supported. {constants.FEEDBACK_LINK}"
ERROR_IO_REQUIRES_WILDCARD = (
"Google Cloud Storage path must contain a wildcard '*' character. See: "
"https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#export_data_statement"
f"{constants.FEEDBACK_LINK}"
)
# Inherits from pandas DataFrame so that we can use the same docstrings.
[docs]
@log_adapter.class_logger
@docs.inherit_docs(vendored_pandas_frame.DataFrame)
class DataFrame:
# internal flag to disable cache at all
_disable_cache_override: bool = False
# Must be above 5000 for pandas to delegate to bigframes for binops
__pandas_priority__ = 15000
[docs]
def __init__(
self,
data=None,
index: vendored_pandas_typing.Axes | None = None,
columns: vendored_pandas_typing.Axes | None = None,
dtype: typing.Optional[
bigframes.dtypes.DtypeString | bigframes.dtypes.Dtype
] = None,
copy: typing.Optional[bool] = None,
*,
session: typing.Optional[bigframes.session.Session] = None,
):
global bigframes
self._query_job: Optional[google.cloud.bigquery.job.QueryJob] = None
if copy is not None and not copy:
raise ValueError(
f"DataFrame constructor only supports copy=True. {constants.FEEDBACK_LINK}"
)
# 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
# Check to see if constructing from BigQuery-backed objects before
# falling back to pandas constructor
block = None
if isinstance(data, blocks.Block):
block = data
elif isinstance(data, DataFrame):
block = data._get_block()
# Dict of Series
elif (
utils.is_dict_like(data)
and len(data) >= 1
and any(
isinstance(data[key], bigframes.series.Series) for key in data.keys()
)
):
if not all(
isinstance(data[key], bigframes.series.Series) for key in data.keys()
):
# TODO(tbergeron): Support local list/series data by converting to memtable.
raise NotImplementedError(
f"Cannot mix Series with other types. {constants.FEEDBACK_LINK}"
)
keys = list(data.keys())
first_label, first_series = keys[0], data[keys[0]]
block = (
typing.cast(bigframes.series.Series, first_series)
._get_block()
.with_column_labels([first_label])
)
for key in keys[1:]:
other = typing.cast(bigframes.series.Series, data[key])
other_block = other._block.with_column_labels([key])
# Pandas will keep original sorting if all indices are aligned.
# We cannot detect this easily however, and so always sort on index
block, _ = block.join( # type:ignore
other_block, how="outer", sort=True
)
if block:
if index is not None:
bf_index = indexes.Index(index)
idx_block = bf_index._block
idx_cols = idx_block.index_columns
block, (_, r_mapping) = block.reset_index().join(
bf_index._block.reset_index(), how="inner"
)
block = block.set_index([r_mapping[idx_col] for idx_col in idx_cols])
if columns:
column_ids = [
block.resolve_label_exact_or_error(label) for label in list(columns)
]
block = block.select_columns(column_ids) # type:ignore
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
import bigframes.pandas
pd_dataframe = pandas.DataFrame(
data=data,
index=index, # type:ignore
columns=columns, # type:ignore
dtype=dtype, # type:ignore
)
if session:
block = session.read_pandas(pd_dataframe)._get_block()
else:
block =