本文整理汇总了Python中pandas.compat.PY3属性的典型用法代码示例。如果您正苦于以下问题:Python compat.PY3属性的具体用法?Python compat.PY3怎么用?Python compat.PY3使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类pandas.compat
的用法示例。
在下文中一共展示了compat.PY3属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_repr
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_repr(self):
i = RangeIndex(5, name='Foo')
result = repr(i)
if PY3:
expected = "RangeIndex(start=0, stop=5, step=1, name='Foo')"
else:
expected = "RangeIndex(start=0, stop=5, step=1, name=u'Foo')"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
i = RangeIndex(5, 0, -1)
result = repr(i)
expected = "RangeIndex(start=5, stop=0, step=-1)"
assert result == expected
result = eval(result)
tm.assert_index_equal(result, i, exact=True)
示例2: test_repr_roundtrip
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_repr_roundtrip(self):
ci = CategoricalIndex(['a', 'b'], categories=['a', 'b'], ordered=True)
str(ci)
tm.assert_index_equal(eval(repr(ci)), ci, exact=True)
# formatting
if PY3:
str(ci)
else:
compat.text_type(ci)
# long format
# this is not reprable
ci = CategoricalIndex(np.random.randint(0, 5, size=100))
if PY3:
str(ci)
else:
compat.text_type(ci)
示例3: test_map_with_string_constructor
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_map_with_string_constructor(self):
raw = [2005, 2007, 2009]
index = PeriodIndex(raw, freq='A')
types = str,
if PY3:
# unicode
types += text_type,
for t in types:
expected = Index(lmap(t, raw))
res = index.map(t)
# should return an Index
assert isinstance(res, Index)
# preserve element types
assert all(isinstance(resi, t) for resi in res)
# lastly, values should compare equal
tm.assert_index_equal(res, expected)
示例4: check_whitelist
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def check_whitelist(obj, df, m):
# check the obj for a particular whitelist m
gb = obj.groupby(df.letters)
f = getattr(type(gb), m)
# name
try:
n = f.__name__
except AttributeError:
return
assert n == m
# qualname
if compat.PY3:
try:
n = f.__qualname__
except AttributeError:
return
assert n.endswith(m)
示例5: test_inplace_ops_identity2
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_inplace_ops_identity2(self, op):
if compat.PY3 and op == 'div':
return
df = DataFrame({'a': [1., 2., 3.],
'b': [1, 2, 3]})
operand = 2
if op in ('and', 'or', 'xor'):
# cannot use floats for boolean ops
df['a'] = [True, False, True]
df_copy = df.copy()
iop = '__i{}__'.format(op)
op = '__{}__'.format(op)
# no id change and value is correct
getattr(df, iop)(operand)
expected = getattr(df_copy, op)(operand)
assert_frame_equal(df, expected)
expected = id(df)
assert id(df) == expected
示例6: test_timestamp
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_timestamp(self):
# GH#17329
# tz-naive --> treat it as if it were UTC for purposes of timestamp()
ts = Timestamp.now()
uts = ts.replace(tzinfo=utc)
assert ts.timestamp() == uts.timestamp()
tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
utsc = tsc.tz_convert('UTC')
# utsc is a different representation of the same time
assert tsc.timestamp() == utsc.timestamp()
if PY3:
# datetime.timestamp() converts in the local timezone
with tm.set_timezone('UTC'):
# should agree with datetime.timestamp method
dt = ts.to_pydatetime()
assert dt.timestamp() == ts.timestamp()
示例7: test_strl_latin1
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_strl_latin1(self):
# GH 23573, correct GSO data to reflect correct size
output = DataFrame([[u'pandas'] * 2, [u'þâÑÐŧ'] * 2],
columns=['var_str', 'var_strl'])
with tm.ensure_clean() as path:
output.to_stata(path, version=117, convert_strl=['var_strl'])
with open(path, 'rb') as reread:
content = reread.read()
expected = u'þâÑÐŧ'
assert expected.encode('latin-1') in content
assert expected.encode('utf-8') in content
gsos = content.split(b'strls')[1][1:-2]
for gso in gsos.split(b'GSO')[1:]:
val = gso.split(b'\x00')[-2]
size = gso[gso.find(b'\x82') + 1]
if not PY3:
size = ord(size)
assert len(val) == size - 1
示例8: test_to_latex_filename
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_to_latex_filename(self, frame):
with tm.ensure_clean('test.tex') as path:
frame.to_latex(path)
with open(path, 'r') as f:
assert frame.to_latex() == f.read()
# test with utf-8 and encoding option (GH 7061)
df = DataFrame([[u'au\xdfgangen']])
with tm.ensure_clean('test.tex') as path:
df.to_latex(path, encoding='utf-8')
with codecs.open(path, 'r', encoding='utf-8') as f:
assert df.to_latex() == f.read()
# test with utf-8 without encoding option
if compat.PY3: # python3: pandas default encoding is utf-8
with tm.ensure_clean('test.tex') as path:
df.to_latex(path)
with codecs.open(path, 'r', encoding='utf-8') as f:
assert df.to_latex() == f.read()
else:
# python2 default encoding is ascii, so an error should be raised
with tm.ensure_clean('test.tex') as path:
with pytest.raises(UnicodeEncodeError):
df.to_latex(path)
示例9: test_variable_width_unicode
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_variable_width_unicode():
if not compat.PY3:
pytest.skip("Bytes-related test - only needs to work on Python 3")
data = """
שלום שלום
ום שלל
של ום
""".strip("\r\n")
encoding = "utf8"
kwargs = dict(header=None, encoding=encoding)
expected = read_fwf(BytesIO(data.encode(encoding)),
colspecs=[(0, 4), (5, 9)], **kwargs)
result = read_fwf(BytesIO(data.encode(encoding)), **kwargs)
tm.assert_frame_equal(result, expected)
示例10: test_fwf_compression
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_fwf_compression(compression_only, infer):
data = """1111111111
2222222222
3333333333""".strip()
compression = compression_only
extension = "gz" if compression == "gzip" else compression
kwargs = dict(widths=[5, 5], names=["one", "two"])
expected = read_fwf(StringIO(data), **kwargs)
if compat.PY3:
data = bytes(data, encoding="utf-8")
with tm.ensure_clean(filename="tmp." + extension) as path:
tm.write_to_compressed(compression, path, data)
if infer is not None:
kwargs["compression"] = "infer" if infer else compression
result = read_fwf(path, **kwargs)
tm.assert_frame_equal(result, expected)
示例11: test_bad_stream_exception
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_bad_stream_exception(all_parsers, csv_dir_path):
# see gh-13652
#
# This test validates that both the Python engine and C engine will
# raise UnicodeDecodeError instead of C engine raising ParserError
# and swallowing the exception that caused read to fail.
path = os.path.join(csv_dir_path, "sauron.SHIFT_JIS.csv")
codec = codecs.lookup("utf-8")
utf8 = codecs.lookup('utf-8')
parser = all_parsers
msg = ("'utf-8' codec can't decode byte" if compat.PY3
else "'utf8' codec can't decode byte")
# Stream must be binary UTF8.
with open(path, "rb") as handle, codecs.StreamRecoder(
handle, utf8.encode, utf8.decode, codec.streamreader,
codec.streamwriter) as stream:
with pytest.raises(UnicodeDecodeError, match=msg):
parser.read_csv(stream)
示例12: test_non_ascii_key
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_non_ascii_key(self):
if compat.PY3:
testjson = (
b'[{"\xc3\x9cnic\xc3\xb8de":0,"sub":{"A":1, "B":2}},' +
b'{"\xc3\x9cnic\xc3\xb8de":1,"sub":{"A":3, "B":4}}]'
).decode('utf8')
else:
testjson = ('[{"\xc3\x9cnic\xc3\xb8de":0,"sub":{"A":1, "B":2}},'
'{"\xc3\x9cnic\xc3\xb8de":1,"sub":{"A":3, "B":4}}]')
testdata = {
u'sub.A': [1, 3],
u'sub.B': [2, 4],
b"\xc3\x9cnic\xc3\xb8de".decode('utf8'): [0, 1]
}
expected = DataFrame(testdata)
result = json_normalize(json.loads(testjson))
tm.assert_frame_equal(result, expected)
示例13: test_columns_dtypes_invalid
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_columns_dtypes_invalid(self, engine):
df = pd.DataFrame({'string': list('abc'),
'int': list(range(1, 4))})
# numeric
df.columns = [0, 1]
self.check_error_on_write(df, engine, ValueError)
if PY3:
# bytes on PY3, on PY2 these are str
df.columns = [b'foo', b'bar']
self.check_error_on_write(df, engine, ValueError)
# python object
df.columns = [datetime.datetime(2011, 1, 1, 0, 0),
datetime.datetime(2011, 1, 1, 1, 1)]
self.check_error_on_write(df, engine, ValueError)
示例14: test_msgpacks_legacy
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def test_msgpacks_legacy(self, current_packers_data, all_packers_data,
legacy_packer, datapath):
version = os.path.basename(os.path.dirname(legacy_packer))
# GH12142 0.17 files packed in P2 can't be read in P3
if (compat.PY3 and version.startswith('0.17.') and
legacy_packer.split('.')[-4][-1] == '2'):
msg = "Files packed in Py2 can't be read in Py3 ({})"
pytest.skip(msg.format(version))
try:
with catch_warnings(record=True):
self.compare(current_packers_data, all_packers_data,
legacy_packer, version)
except ImportError:
# blosc not installed
pass
示例15: _add_arithmetic_ops
# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import PY3 [as 别名]
def _add_arithmetic_ops(cls):
cls.__add__ = cls._create_arithmetic_method(operator.add)
cls.__radd__ = cls._create_arithmetic_method(ops.radd)
cls.__sub__ = cls._create_arithmetic_method(operator.sub)
cls.__rsub__ = cls._create_arithmetic_method(ops.rsub)
cls.__mul__ = cls._create_arithmetic_method(operator.mul)
cls.__rmul__ = cls._create_arithmetic_method(ops.rmul)
cls.__pow__ = cls._create_arithmetic_method(operator.pow)
cls.__rpow__ = cls._create_arithmetic_method(ops.rpow)
cls.__mod__ = cls._create_arithmetic_method(operator.mod)
cls.__rmod__ = cls._create_arithmetic_method(ops.rmod)
cls.__floordiv__ = cls._create_arithmetic_method(operator.floordiv)
cls.__rfloordiv__ = cls._create_arithmetic_method(ops.rfloordiv)
cls.__truediv__ = cls._create_arithmetic_method(operator.truediv)
cls.__rtruediv__ = cls._create_arithmetic_method(ops.rtruediv)
if not PY3:
cls.__div__ = cls._create_arithmetic_method(operator.div)
cls.__rdiv__ = cls._create_arithmetic_method(ops.rdiv)
cls.__divmod__ = cls._create_arithmetic_method(divmod)
cls.__rdivmod__ = cls._create_arithmetic_method(ops.rdivmod)