本文整理汇总了Python中pandas.core.dtypes.cast.find_common_type方法的典型用法代码示例。如果您正苦于以下问题:Python cast.find_common_type方法的具体用法?Python cast.find_common_type怎么用?Python cast.find_common_type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas.core.dtypes.cast
的用法示例。
在下文中一共展示了cast.find_common_type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: infer_index_value
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def infer_index_value(left_index_value, right_index_value):
from .core import IndexValue
if isinstance(left_index_value.value, IndexValue.RangeIndex) and \
isinstance(right_index_value.value, IndexValue.RangeIndex):
if left_index_value.value.slice == right_index_value.value.slice:
return left_index_value
return parse_index(pd.Int64Index([]), left_index_value, right_index_value)
# when left index and right index is identical, and both of them are elements unique,
# we can infer that the out index should be identical also
if left_index_value.is_unique and right_index_value.is_unique and \
left_index_value.key == right_index_value.key:
return left_index_value
left_index = left_index_value.to_pandas()
right_index = right_index_value.to_pandas()
out_index = pd.Index([], dtype=find_common_type([left_index.dtype, right_index.dtype]))
return parse_index(out_index, left_index_value, right_index_value)
示例2: test_numpy_dtypes
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_numpy_dtypes(source_dtypes, expected_common_dtype):
assert find_common_type(source_dtypes) == expected_common_dtype
示例3: test_raises_empty_input
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_raises_empty_input():
with pytest.raises(ValueError, match="no types given"):
find_common_type([])
示例4: test_categorical_dtype
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_categorical_dtype(dtypes, exp_type):
assert find_common_type(dtypes) == exp_type
示例5: test_datetimetz_dtype_match
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_datetimetz_dtype_match():
dtype = DatetimeTZDtype(unit="ns", tz="US/Eastern")
assert find_common_type([dtype, dtype]) == "datetime64[ns, US/Eastern]"
示例6: test_datetimetz_dtype_mismatch
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_datetimetz_dtype_mismatch(dtype2):
dtype = DatetimeTZDtype(unit="ns", tz="US/Eastern")
assert find_common_type([dtype, dtype2]) == np.object
assert find_common_type([dtype2, dtype]) == np.object
示例7: test_period_dtype_mismatch
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def test_period_dtype_mismatch(dtype2):
dtype = PeriodDtype(freq="D")
assert find_common_type([dtype, dtype2]) == np.object
assert find_common_type([dtype2, dtype]) == np.object
示例8: to_coo
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def to_coo(self):
"""
Return the contents of the frame as a sparse SciPy COO matrix.
.. versionadded:: 0.20.0
Returns
-------
coo_matrix : scipy.sparse.spmatrix
If the caller is heterogeneous and contains booleans or objects,
the result will be of dtype=object. See Notes.
Notes
-----
The dtype will be the lowest-common-denominator type (implicit
upcasting); that is to say if the dtypes (even of numeric types)
are mixed, the one that accommodates all will be chosen.
e.g. If the dtypes are float16 and float32, dtype will be upcast to
float32. By numpy.find_common_type convention, mixing int64 and
and uint64 will result in a float64 dtype.
"""
try:
from scipy.sparse import coo_matrix
except ImportError:
raise ImportError('Scipy is not installed')
dtype = find_common_type(self.dtypes)
cols, rows, datas = [], [], []
for col, name in enumerate(self):
s = self[name]
row = s.sp_index.to_int_index().indices
cols.append(np.repeat(col, len(row)))
rows.append(row)
datas.append(s.sp_values.astype(dtype, copy=False))
cols = np.concatenate(cols)
rows = np.concatenate(rows)
datas = np.concatenate(datas)
return coo_matrix((datas, (rows, cols)), shape=self.shape)
示例9: _arith_method_PANEL
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def _arith_method_PANEL(op, name, str_rep=None, fill_zeros=None,
default_axis=None, **eval_kwargs):
# copied from Series na_op above, but without unnecessary branch for
# non-scalar
def na_op(x, y):
import pandas.core.computation.expressions as expressions
try:
result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs)
except TypeError:
# TODO: might need to find_common_type here?
result = np.empty(len(x), dtype=x.dtype)
mask = notna(x)
result[mask] = op(x[mask], y)
result, changed = maybe_upcast_putmask(result, ~mask, np.nan)
result = missing.fill_zeros(result, x, y, name, fill_zeros)
return result
# work only for scalars
def f(self, other):
if not is_scalar(other):
raise ValueError('Simple arithmetic with {name} can only be '
'done with scalar values'
.format(name=self._constructor.__name__))
return self._combine(other, op)
f.__name__ = name
return f
示例10: getFPType
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def getFPType(X):
try:
from pandas import DataFrame
from pandas.core.dtypes.cast import find_common_type
if isinstance(X, DataFrame):
dt = find_common_type(X.dtypes)
return parse_dtype(dt)
except ImportError:
pass
dt = getattr(X, 'dtype', None)
return parse_dtype(dt)
示例11: get_dtype
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def get_dtype(X):
try:
from pandas.core.dtypes.cast import find_common_type
return find_common_type(X.dtypes) if is_DataFrame(X) else X.dtype
except ImportError:
return getattr(X, "dtype", None)
示例12: combine_dtypes
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def combine_dtypes(cls, list_of_dtypes, column_names):
# Compute dtypes by getting collecting and combining all of the partitions. The
# reported dtypes from differing rows can be different based on the inference in
# the limited data seen by each worker. We use pandas to compute the exact dtype
# over the whole column for each column.
dtypes = (
pandas.concat(ray.get(list_of_dtypes), axis=1)
.apply(lambda row: find_common_type(row.values), axis=1)
.squeeze(axis=0)
)
dtypes.index = column_names
return dtypes
示例13: find_common_type_cat
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def find_common_type_cat(types):
if all(isinstance(t, pandas.CategoricalDtype) for t in types):
if all(t.ordered for t in types):
return pandas.CategoricalDtype(
np.sort(np.unique([c for t in types for c in t.categories])[0]),
ordered=True,
)
return union_categoricals(
[pandas.Categorical([], dtype=t) for t in types],
sort_categories=all(t.ordered for t in types),
).dtype
else:
return find_common_type(types)
示例14: to_coo
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def to_coo(self):
"""
Return the contents of the frame as a sparse SciPy COO matrix.
.. versionadded:: 0.20.0
Returns
-------
coo_matrix : scipy.sparse.spmatrix
If the caller is heterogeneous and contains booleans or objects,
the result will be of dtype=object. See Notes.
Notes
-----
The dtype will be the lowest-common-denominator type (implicit
upcasting); that is to say if the dtypes (even of numeric types)
are mixed, the one that accommodates all will be chosen.
e.g. If the dtypes are float16 and float32, dtype will be upcast to
float32. By numpy.find_common_type convention, mixing int64 and
and uint64 will result in a float64 dtype.
"""
try:
from scipy.sparse import coo_matrix
except ImportError:
raise ImportError('Scipy is not installed')
dtype = find_common_type(self.dtypes)
if isinstance(dtype, SparseDtype):
dtype = dtype.subtype
cols, rows, datas = [], [], []
for col, name in enumerate(self):
s = self[name]
row = s.sp_index.to_int_index().indices
cols.append(np.repeat(col, len(row)))
rows.append(row)
datas.append(s.sp_values.astype(dtype, copy=False))
cols = np.concatenate(cols)
rows = np.concatenate(rows)
datas = np.concatenate(datas)
return coo_matrix((datas, (rows, cols)), shape=self.shape)
示例15: __call__
# 需要导入模块: from pandas.core.dtypes import cast [as 别名]
# 或者: from pandas.core.dtypes.cast import find_common_type [as 别名]
def __call__(self, inp):
inputs = [inp] + filter_inputs(self._indexes)
shape = []
sizes = []
index_value = columns_value = dtypes = None
for ax, index in enumerate(self._indexes):
param = self._calc_param(inp, ax, index)
size = param.get('shape')
sizes.append(size)
if size is not None:
shape.append(size)
if ax == 0:
index_value = param.get('index_value')
else:
columns_value = param.get('index_value')
dtypes = param.get('dtypes')
shape = tuple(shape)
if len(shape) == 0:
# scalar
if isinstance(inp, DATAFRAME_TYPE):
dtype = inp.dtypes[self._indexes[1]]
else:
dtype = inp.dtype
return self.new_scalar(inputs, dtype=dtype)
elif len(shape) == 1:
# series
if isinstance(inp, DATAFRAME_TYPE):
if sizes[0] is None:
# label on axis 0
dtype = find_common_type(dtypes)
return self.new_series(inputs, shape=shape, dtype=dtype,
index_value=columns_value, name=self._indexes[0])
else:
# label on axis 1
dtype = inp.dtypes[self._indexes[1]]
return self.new_series(inputs, shape=shape, dtype=dtype,
index_value=index_value, name=self._indexes[1])
else:
return self.new_series(inputs, shape=shape, dtype=inp.dtype,
index_value=index_value, name=inp.name)
else:
# dataframe
return self.new_dataframe(inputs, shape=shape, dtypes=dtypes,
index_value=index_value, columns_value=columns_value)