本文整理汇总了Python中pandas.compat.PY2属性的典型用法代码示例。如果您正苦于以下问题:Python compat.PY2属性的具体用法?Python compat.PY2怎么用?Python compat.PY2使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类pandas.compat
的用法示例。
在下文中一共展示了compat.PY2属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_iteration_open_handle
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_iteration_open_handle(all_parsers):
parser = all_parsers
kwargs = dict(squeeze=True, header=None)
with tm.ensure_clean() as path:
with open(path, "wb" if compat.PY2 else "w") as f:
f.write("AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG")
with open(path, "rb" if compat.PY2 else "r") as f:
for line in f:
if "CCC" in line:
break
if parser.engine == "c" and compat.PY2:
msg = "Mixing iteration and read methods would lose data"
with pytest.raises(ValueError, match=msg):
parser.read_csv(f, **kwargs)
else:
result = parser.read_csv(f, **kwargs)
expected = Series(["DDD", "EEE", "FFF", "GGG"], name=0)
tm.assert_series_equal(result, expected)
示例2: setup_method
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def setup_method(self, datapath):
self.dirpath = datapath("io", "sas", "data")
self.data = []
self.test_ix = [list(range(1, 16)), [16]]
for j in 1, 2:
fname = os.path.join(
self.dirpath, "test_sas7bdat_{j}.csv".format(j=j))
df = pd.read_csv(fname)
epoch = pd.datetime(1960, 1, 1)
t1 = pd.to_timedelta(df["Column4"], unit='d')
df["Column4"] = epoch + t1
t2 = pd.to_timedelta(df["Column12"], unit='d')
df["Column12"] = epoch + t2
for k in range(df.shape[1]):
col = df.iloc[:, k]
if col.dtype == np.int64:
df.iloc[:, k] = df.iloc[:, k].astype(np.float64)
elif col.dtype == np.dtype('O'):
if PY2:
f = lambda x: (x.decode('utf-8') if
isinstance(x, str) else x)
df.iloc[:, k] = df.iloc[:, k].apply(f)
self.data.append(df)
示例3: test_cant_compare_tz_naive_w_aware_explicit_pytz
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_cant_compare_tz_naive_w_aware_explicit_pytz(self):
# see gh-1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz=utc)
pytest.raises(Exception, a.__eq__, b)
pytest.raises(Exception, a.__ne__, b)
pytest.raises(Exception, a.__lt__, b)
pytest.raises(Exception, a.__gt__, b)
pytest.raises(Exception, b.__eq__, a)
pytest.raises(Exception, b.__ne__, a)
pytest.raises(Exception, b.__lt__, a)
pytest.raises(Exception, b.__gt__, a)
if PY2:
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
else:
assert not a == b.to_pydatetime()
assert not a.to_pydatetime() == b
示例4: test_cant_compare_tz_naive_w_aware_dateutil
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_cant_compare_tz_naive_w_aware_dateutil(self):
# see gh-1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz=tzutc())
pytest.raises(Exception, a.__eq__, b)
pytest.raises(Exception, a.__ne__, b)
pytest.raises(Exception, a.__lt__, b)
pytest.raises(Exception, a.__gt__, b)
pytest.raises(Exception, b.__eq__, a)
pytest.raises(Exception, b.__ne__, a)
pytest.raises(Exception, b.__lt__, a)
pytest.raises(Exception, b.__gt__, a)
if PY2:
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
else:
assert not a == b.to_pydatetime()
assert not a.to_pydatetime() == b
示例5: to_latex
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def to_latex(self, column_format=None, longtable=False, encoding=None,
multicolumn=False, multicolumn_format=None, multirow=False):
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
from pandas.io.formats.latex import LatexFormatter
latex_renderer = LatexFormatter(self, column_format=column_format,
longtable=longtable,
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow)
if encoding is None:
encoding = 'ascii' if compat.PY2 else 'utf-8'
if hasattr(self.buf, 'write'):
latex_renderer.write_result(self.buf)
elif isinstance(self.buf, compat.string_types):
import codecs
with codecs.open(self.buf, 'w', encoding=encoding) as f:
latex_renderer.write_result(f)
else:
raise TypeError('buf is not a file name and it has no write '
'method')
示例6: to_latex
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def to_latex(self, column_format=None, longtable=False, encoding=None,
multicolumn=False, multicolumn_format=None, multirow=False):
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
"""
latex_renderer = LatexFormatter(self, column_format=column_format,
longtable=longtable,
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow)
if encoding is None:
encoding = 'ascii' if compat.PY2 else 'utf-8'
if hasattr(self.buf, 'write'):
latex_renderer.write_result(self.buf)
elif isinstance(self.buf, compat.string_types):
import codecs
with codecs.open(self.buf, 'w', encoding=encoding) as f:
latex_renderer.write_result(f)
else:
raise TypeError('buf is not a file name and it has no write '
'method')
示例7: setup_method
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def setup_method(self, method):
self.dirpath = tm.get_data_path()
self.data = []
self.test_ix = [list(range(1, 16)), [16]]
for j in 1, 2:
fname = os.path.join(self.dirpath, "test_sas7bdat_%d.csv" % j)
df = pd.read_csv(fname)
epoch = pd.datetime(1960, 1, 1)
t1 = pd.to_timedelta(df["Column4"], unit='d')
df["Column4"] = epoch + t1
t2 = pd.to_timedelta(df["Column12"], unit='d')
df["Column12"] = epoch + t2
for k in range(df.shape[1]):
col = df.iloc[:, k]
if col.dtype == np.int64:
df.iloc[:, k] = df.iloc[:, k].astype(np.float64)
elif col.dtype == np.dtype('O'):
if PY2:
f = lambda x: (x.decode('utf-8') if
isinstance(x, str) else x)
df.iloc[:, k] = df.iloc[:, k].apply(f)
self.data.append(df)
示例8: test_arith_series_with_scalar
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
if (compat.PY2 and
all_arithmetic_operators in {'__div__', '__rdiv__'}):
raise pytest.skip(
"Matching NumPy int / int -> float behavior."
)
super(TestArithmetics, self).test_arith_series_with_scalar(
data, all_arithmetic_operators
)
示例9: test_arith_series_with_array
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_arith_series_with_array(self, data, all_arithmetic_operators):
if (compat.PY2 and
all_arithmetic_operators in {'__div__', '__rdiv__'}):
raise pytest.skip(
"Matching NumPy int / int -> float behavior."
)
super(TestArithmetics, self).test_arith_series_with_array(
data, all_arithmetic_operators
)
示例10: test_concat_order
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_concat_order(self):
# GH 17344
dfs = [pd.DataFrame(index=range(3), columns=['a', 1, None])]
dfs += [pd.DataFrame(index=range(3), columns=[None, 1, 'a'])
for i in range(100)]
result = pd.concat(dfs, sort=True).columns
if PY2:
# Different sort order between incomparable objects between
# python 2 and python3 via Index.union.
expected = dfs[1].columns
else:
expected = dfs[0].columns
tm.assert_index_equal(result, expected)
示例11: any_allowed_skipna_inferred_dtype
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def any_allowed_skipna_inferred_dtype(request):
"""
Fixture for all (inferred) dtypes allowed in StringMethods.__init__
The covered (inferred) types are:
* 'string'
* 'unicode' (if PY2)
* 'empty'
* 'bytes' (if PY3)
* 'mixed'
* 'mixed-integer'
Returns
-------
inferred_dtype : str
The string for the inferred dtype from _libs.lib.infer_dtype
values : np.ndarray
An array of object dtype that will be inferred to have
`inferred_dtype`
Examples
--------
>>> import pandas._libs.lib as lib
>>>
>>> def test_something(any_allowed_skipna_inferred_dtype):
... inferred_dtype, values = any_allowed_skipna_inferred_dtype
... # will pass
... assert lib.infer_dtype(values, skipna=True) == inferred_dtype
"""
inferred_dtype, values = request.param
values = np.array(values, dtype=object) # object dtype to avoid casting
# correctness of inference tested in tests/dtypes/test_inference.py
return inferred_dtype, values
示例12: test_replace_callable
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_replace_callable(self):
# GH 15055
values = Series(['fooBAD__barBAD', NA])
# test with callable
repl = lambda m: m.group(0).swapcase()
result = values.str.replace('[a-z][A-Z]{2}', repl, n=2)
exp = Series(['foObaD__baRbaD', NA])
tm.assert_series_equal(result, exp)
# test with wrong number of arguments, raising an error
if compat.PY2:
p_err = r'takes (no|(exactly|at (least|most)) ?\d+) arguments?'
else:
p_err = (r'((takes)|(missing)) (?(2)from \d+ to )?\d+ '
r'(?(3)required )positional arguments?')
repl = lambda: None
with pytest.raises(TypeError, match=p_err):
values.str.replace('a', repl)
repl = lambda m, x: None
with pytest.raises(TypeError, match=p_err):
values.str.replace('a', repl)
repl = lambda m, x, y=None: None
with pytest.raises(TypeError, match=p_err):
values.str.replace('a', repl)
# test regex named groups
values = Series(['Foo Bar Baz', NA])
pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)"
repl = lambda m: m.group('middle').swapcase()
result = values.str.replace(pat, repl)
exp = Series(['bAR', NA])
tm.assert_series_equal(result, exp)
示例13: test_infer_dtype_bytes
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_infer_dtype_bytes(self):
compare = 'string' if PY2 else 'bytes'
# string array of bytes
arr = np.array(list('abc'), dtype='S1')
assert lib.infer_dtype(arr, skipna=True) == compare
# object array of bytes
arr = arr.astype(object)
assert lib.infer_dtype(arr, skipna=True) == compare
# object array of bytes with missing values
assert lib.infer_dtype([b'a', np.nan, b'c'], skipna=True) == compare
示例14: test_unicode
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_unicode(self):
arr = [u'a', np.nan, u'c']
result = lib.infer_dtype(arr, skipna=False)
assert result == 'mixed'
arr = [u'a', np.nan, u'c']
result = lib.infer_dtype(arr, skipna=True)
expected = 'unicode' if PY2 else 'string'
assert result == expected
示例15: test_cant_compare_tz_naive_w_aware
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY2 [as 别名]
def test_cant_compare_tz_naive_w_aware(self, utc_fixture):
# see GH#1404
a = Timestamp('3/12/2012')
b = Timestamp('3/12/2012', tz=utc_fixture)
with pytest.raises(TypeError):
a == b
with pytest.raises(TypeError):
a != b
with pytest.raises(TypeError):
a < b
with pytest.raises(TypeError):
a <= b
with pytest.raises(TypeError):
a > b
with pytest.raises(TypeError):
a >= b
with pytest.raises(TypeError):
b == a
with pytest.raises(TypeError):
b != a
with pytest.raises(TypeError):
b < a
with pytest.raises(TypeError):
b <= a
with pytest.raises(TypeError):
b > a
with pytest.raises(TypeError):
b >= a
if PY2:
with pytest.raises(TypeError):
a == b.to_pydatetime()
with pytest.raises(TypeError):
a.to_pydatetime() == b
else:
assert not a == b.to_pydatetime()
assert not a.to_pydatetime() == b