Add files using upload-large-folder tool
Browse files- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_quoting.py +158 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_read_fwf.py +580 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_skiprows.py +222 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_textreader.py +353 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_unsupported.py +140 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_usecols.py +534 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_duplicates.py +148 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_internals.py +343 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_io.py +267 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/__init__.py +0 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/test_pivot.py +52 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/test_reshape.py +42 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tools/__init__.py +0 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tools/test_numeric.py +440 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/__init__.py +0 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/test_frequencies.py +793 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/test_holiday.py +382 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_api.py +40 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_array_to_datetime.py +156 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_ccalendar.py +25 -0
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_quoting.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests that quoting specifications are properly handled
|
| 5 |
+
during parsing for all of the parsers defined in parsers.py
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import csv
|
| 9 |
+
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from pandas.compat import PY2, StringIO, u
|
| 13 |
+
from pandas.errors import ParserError
|
| 14 |
+
|
| 15 |
+
from pandas import DataFrame
|
| 16 |
+
import pandas.util.testing as tm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.mark.parametrize("kwargs,msg", [
|
| 20 |
+
(dict(quotechar="foo"), '"quotechar" must be a(n)? 1-character string'),
|
| 21 |
+
(dict(quotechar=None, quoting=csv.QUOTE_MINIMAL),
|
| 22 |
+
"quotechar must be set if quoting enabled"),
|
| 23 |
+
(dict(quotechar=2), '"quotechar" must be string, not int')
|
| 24 |
+
])
|
| 25 |
+
def test_bad_quote_char(all_parsers, kwargs, msg):
|
| 26 |
+
data = "1,2,3"
|
| 27 |
+
parser = all_parsers
|
| 28 |
+
|
| 29 |
+
with pytest.raises(TypeError, match=msg):
|
| 30 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@pytest.mark.parametrize("quoting,msg", [
|
| 34 |
+
("foo", '"quoting" must be an integer'),
|
| 35 |
+
(5, 'bad "quoting" value'), # quoting must be in the range [0, 3]
|
| 36 |
+
])
|
| 37 |
+
def test_bad_quoting(all_parsers, quoting, msg):
|
| 38 |
+
data = "1,2,3"
|
| 39 |
+
parser = all_parsers
|
| 40 |
+
|
| 41 |
+
with pytest.raises(TypeError, match=msg):
|
| 42 |
+
parser.read_csv(StringIO(data), quoting=quoting)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_quote_char_basic(all_parsers):
|
| 46 |
+
parser = all_parsers
|
| 47 |
+
data = 'a,b,c\n1,2,"cat"'
|
| 48 |
+
expected = DataFrame([[1, 2, "cat"]],
|
| 49 |
+
columns=["a", "b", "c"])
|
| 50 |
+
|
| 51 |
+
result = parser.read_csv(StringIO(data), quotechar='"')
|
| 52 |
+
tm.assert_frame_equal(result, expected)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@pytest.mark.parametrize("quote_char", ["~", "*", "%", "$", "@", "P"])
|
| 56 |
+
def test_quote_char_various(all_parsers, quote_char):
|
| 57 |
+
parser = all_parsers
|
| 58 |
+
expected = DataFrame([[1, 2, "cat"]],
|
| 59 |
+
columns=["a", "b", "c"])
|
| 60 |
+
|
| 61 |
+
data = 'a,b,c\n1,2,"cat"'
|
| 62 |
+
new_data = data.replace('"', quote_char)
|
| 63 |
+
|
| 64 |
+
result = parser.read_csv(StringIO(new_data), quotechar=quote_char)
|
| 65 |
+
tm.assert_frame_equal(result, expected)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@pytest.mark.parametrize("quoting", [csv.QUOTE_MINIMAL, csv.QUOTE_NONE])
|
| 69 |
+
@pytest.mark.parametrize("quote_char", ["", None])
|
| 70 |
+
def test_null_quote_char(all_parsers, quoting, quote_char):
|
| 71 |
+
kwargs = dict(quotechar=quote_char, quoting=quoting)
|
| 72 |
+
data = "a,b,c\n1,2,3"
|
| 73 |
+
parser = all_parsers
|
| 74 |
+
|
| 75 |
+
if quoting != csv.QUOTE_NONE:
|
| 76 |
+
# Sanity checking.
|
| 77 |
+
msg = "quotechar must be set if quoting enabled"
|
| 78 |
+
|
| 79 |
+
with pytest.raises(TypeError, match=msg):
|
| 80 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 81 |
+
else:
|
| 82 |
+
expected = DataFrame([[1, 2, 3]], columns=["a", "b", "c"])
|
| 83 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 84 |
+
tm.assert_frame_equal(result, expected)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize("kwargs,exp_data", [
|
| 88 |
+
(dict(), [[1, 2, "foo"]]), # Test default.
|
| 89 |
+
|
| 90 |
+
# QUOTE_MINIMAL only applies to CSV writing, so no effect on reading.
|
| 91 |
+
(dict(quotechar='"', quoting=csv.QUOTE_MINIMAL), [[1, 2, "foo"]]),
|
| 92 |
+
|
| 93 |
+
# QUOTE_MINIMAL only applies to CSV writing, so no effect on reading.
|
| 94 |
+
(dict(quotechar='"', quoting=csv.QUOTE_ALL), [[1, 2, "foo"]]),
|
| 95 |
+
|
| 96 |
+
# QUOTE_NONE tells the reader to do no special handling
|
| 97 |
+
# of quote characters and leave them alone.
|
| 98 |
+
(dict(quotechar='"', quoting=csv.QUOTE_NONE), [[1, 2, '"foo"']]),
|
| 99 |
+
|
| 100 |
+
# QUOTE_NONNUMERIC tells the reader to cast
|
| 101 |
+
# all non-quoted fields to float
|
| 102 |
+
(dict(quotechar='"', quoting=csv.QUOTE_NONNUMERIC), [[1.0, 2.0, "foo"]])
|
| 103 |
+
])
|
| 104 |
+
def test_quoting_various(all_parsers, kwargs, exp_data):
|
| 105 |
+
data = '1,2,"foo"'
|
| 106 |
+
parser = all_parsers
|
| 107 |
+
columns = ["a", "b", "c"]
|
| 108 |
+
|
| 109 |
+
result = parser.read_csv(StringIO(data), names=columns, **kwargs)
|
| 110 |
+
expected = DataFrame(exp_data, columns=columns)
|
| 111 |
+
tm.assert_frame_equal(result, expected)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@pytest.mark.parametrize("doublequote,exp_data", [
|
| 115 |
+
(True, [[3, '4 " 5']]),
|
| 116 |
+
(False, [[3, '4 " 5"']]),
|
| 117 |
+
])
|
| 118 |
+
def test_double_quote(all_parsers, doublequote, exp_data):
|
| 119 |
+
parser = all_parsers
|
| 120 |
+
data = 'a,b\n3,"4 "" 5"'
|
| 121 |
+
|
| 122 |
+
result = parser.read_csv(StringIO(data), quotechar='"',
|
| 123 |
+
doublequote=doublequote)
|
| 124 |
+
expected = DataFrame(exp_data, columns=["a", "b"])
|
| 125 |
+
tm.assert_frame_equal(result, expected)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@pytest.mark.parametrize("quotechar", [
|
| 129 |
+
u('"'),
|
| 130 |
+
pytest.param(u('\u0001'), marks=pytest.mark.skipif(
|
| 131 |
+
PY2, reason="Python 2.x does not handle unicode well."))])
|
| 132 |
+
def test_quotechar_unicode(all_parsers, quotechar):
|
| 133 |
+
# see gh-14477
|
| 134 |
+
data = "a\n1"
|
| 135 |
+
parser = all_parsers
|
| 136 |
+
expected = DataFrame({"a": [1]})
|
| 137 |
+
|
| 138 |
+
result = parser.read_csv(StringIO(data), quotechar=quotechar)
|
| 139 |
+
tm.assert_frame_equal(result, expected)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@pytest.mark.parametrize("balanced", [True, False])
|
| 143 |
+
def test_unbalanced_quoting(all_parsers, balanced):
|
| 144 |
+
# see gh-22789.
|
| 145 |
+
parser = all_parsers
|
| 146 |
+
data = "a,b,c\n1,2,\"3"
|
| 147 |
+
|
| 148 |
+
if balanced:
|
| 149 |
+
# Re-balance the quoting and read in without errors.
|
| 150 |
+
expected = DataFrame([[1, 2, 3]], columns=["a", "b", "c"])
|
| 151 |
+
result = parser.read_csv(StringIO(data + '"'))
|
| 152 |
+
tm.assert_frame_equal(result, expected)
|
| 153 |
+
else:
|
| 154 |
+
msg = ("EOF inside string starting at row 1" if parser.engine == "c"
|
| 155 |
+
else "unexpected end of data")
|
| 156 |
+
|
| 157 |
+
with pytest.raises(ParserError, match=msg):
|
| 158 |
+
parser.read_csv(StringIO(data))
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_read_fwf.py
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests the 'read_fwf' function in parsers.py. This
|
| 5 |
+
test suite is independent of the others because the
|
| 6 |
+
engine is set to 'python-fwf' internally.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
import pandas.compat as compat
|
| 15 |
+
from pandas.compat import BytesIO, StringIO
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
from pandas import DataFrame, DatetimeIndex
|
| 19 |
+
import pandas.util.testing as tm
|
| 20 |
+
|
| 21 |
+
from pandas.io.parsers import EmptyDataError, read_csv, read_fwf
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_basic():
|
| 25 |
+
data = """\
|
| 26 |
+
A B C D
|
| 27 |
+
201158 360.242940 149.910199 11950.7
|
| 28 |
+
201159 444.953632 166.985655 11788.4
|
| 29 |
+
201160 364.136849 183.628767 11806.2
|
| 30 |
+
201161 413.836124 184.375703 11916.8
|
| 31 |
+
201162 502.953953 173.237159 12468.3
|
| 32 |
+
"""
|
| 33 |
+
result = read_fwf(StringIO(data))
|
| 34 |
+
expected = DataFrame([[201158, 360.242940, 149.910199, 11950.7],
|
| 35 |
+
[201159, 444.953632, 166.985655, 11788.4],
|
| 36 |
+
[201160, 364.136849, 183.628767, 11806.2],
|
| 37 |
+
[201161, 413.836124, 184.375703, 11916.8],
|
| 38 |
+
[201162, 502.953953, 173.237159, 12468.3]],
|
| 39 |
+
columns=["A", "B", "C", "D"])
|
| 40 |
+
tm.assert_frame_equal(result, expected)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_colspecs():
|
| 44 |
+
data = """\
|
| 45 |
+
A B C D E
|
| 46 |
+
201158 360.242940 149.910199 11950.7
|
| 47 |
+
201159 444.953632 166.985655 11788.4
|
| 48 |
+
201160 364.136849 183.628767 11806.2
|
| 49 |
+
201161 413.836124 184.375703 11916.8
|
| 50 |
+
201162 502.953953 173.237159 12468.3
|
| 51 |
+
"""
|
| 52 |
+
colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]
|
| 53 |
+
result = read_fwf(StringIO(data), colspecs=colspecs)
|
| 54 |
+
|
| 55 |
+
expected = DataFrame([[2011, 58, 360.242940, 149.910199, 11950.7],
|
| 56 |
+
[2011, 59, 444.953632, 166.985655, 11788.4],
|
| 57 |
+
[2011, 60, 364.136849, 183.628767, 11806.2],
|
| 58 |
+
[2011, 61, 413.836124, 184.375703, 11916.8],
|
| 59 |
+
[2011, 62, 502.953953, 173.237159, 12468.3]],
|
| 60 |
+
columns=["A", "B", "C", "D", "E"])
|
| 61 |
+
tm.assert_frame_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_widths():
|
| 65 |
+
data = """\
|
| 66 |
+
A B C D E
|
| 67 |
+
2011 58 360.242940 149.910199 11950.7
|
| 68 |
+
2011 59 444.953632 166.985655 11788.4
|
| 69 |
+
2011 60 364.136849 183.628767 11806.2
|
| 70 |
+
2011 61 413.836124 184.375703 11916.8
|
| 71 |
+
2011 62 502.953953 173.237159 12468.3
|
| 72 |
+
"""
|
| 73 |
+
result = read_fwf(StringIO(data), widths=[5, 5, 13, 13, 7])
|
| 74 |
+
|
| 75 |
+
expected = DataFrame([[2011, 58, 360.242940, 149.910199, 11950.7],
|
| 76 |
+
[2011, 59, 444.953632, 166.985655, 11788.4],
|
| 77 |
+
[2011, 60, 364.136849, 183.628767, 11806.2],
|
| 78 |
+
[2011, 61, 413.836124, 184.375703, 11916.8],
|
| 79 |
+
[2011, 62, 502.953953, 173.237159, 12468.3]],
|
| 80 |
+
columns=["A", "B", "C", "D", "E"])
|
| 81 |
+
tm.assert_frame_equal(result, expected)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_non_space_filler():
|
| 85 |
+
# From Thomas Kluyver:
|
| 86 |
+
#
|
| 87 |
+
# Apparently, some non-space filler characters can be seen, this is
|
| 88 |
+
# supported by specifying the 'delimiter' character:
|
| 89 |
+
#
|
| 90 |
+
# http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html
|
| 91 |
+
data = """\
|
| 92 |
+
A~~~~B~~~~C~~~~~~~~~~~~D~~~~~~~~~~~~E
|
| 93 |
+
201158~~~~360.242940~~~149.910199~~~11950.7
|
| 94 |
+
201159~~~~444.953632~~~166.985655~~~11788.4
|
| 95 |
+
201160~~~~364.136849~~~183.628767~~~11806.2
|
| 96 |
+
201161~~~~413.836124~~~184.375703~~~11916.8
|
| 97 |
+
201162~~~~502.953953~~~173.237159~~~12468.3
|
| 98 |
+
"""
|
| 99 |
+
colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]
|
| 100 |
+
result = read_fwf(StringIO(data), colspecs=colspecs, delimiter="~")
|
| 101 |
+
|
| 102 |
+
expected = DataFrame([[2011, 58, 360.242940, 149.910199, 11950.7],
|
| 103 |
+
[2011, 59, 444.953632, 166.985655, 11788.4],
|
| 104 |
+
[2011, 60, 364.136849, 183.628767, 11806.2],
|
| 105 |
+
[2011, 61, 413.836124, 184.375703, 11916.8],
|
| 106 |
+
[2011, 62, 502.953953, 173.237159, 12468.3]],
|
| 107 |
+
columns=["A", "B", "C", "D", "E"])
|
| 108 |
+
tm.assert_frame_equal(result, expected)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_over_specified():
|
| 112 |
+
data = """\
|
| 113 |
+
A B C D E
|
| 114 |
+
201158 360.242940 149.910199 11950.7
|
| 115 |
+
201159 444.953632 166.985655 11788.4
|
| 116 |
+
201160 364.136849 183.628767 11806.2
|
| 117 |
+
201161 413.836124 184.375703 11916.8
|
| 118 |
+
201162 502.953953 173.237159 12468.3
|
| 119 |
+
"""
|
| 120 |
+
colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]
|
| 121 |
+
|
| 122 |
+
with pytest.raises(ValueError, match="must specify only one of"):
|
| 123 |
+
read_fwf(StringIO(data), colspecs=colspecs, widths=[6, 10, 10, 7])
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_under_specified():
|
| 127 |
+
data = """\
|
| 128 |
+
A B C D E
|
| 129 |
+
201158 360.242940 149.910199 11950.7
|
| 130 |
+
201159 444.953632 166.985655 11788.4
|
| 131 |
+
201160 364.136849 183.628767 11806.2
|
| 132 |
+
201161 413.836124 184.375703 11916.8
|
| 133 |
+
201162 502.953953 173.237159 12468.3
|
| 134 |
+
"""
|
| 135 |
+
with pytest.raises(ValueError, match="Must specify either"):
|
| 136 |
+
read_fwf(StringIO(data), colspecs=None, widths=None)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_read_csv_compat():
|
| 140 |
+
csv_data = """\
|
| 141 |
+
A,B,C,D,E
|
| 142 |
+
2011,58,360.242940,149.910199,11950.7
|
| 143 |
+
2011,59,444.953632,166.985655,11788.4
|
| 144 |
+
2011,60,364.136849,183.628767,11806.2
|
| 145 |
+
2011,61,413.836124,184.375703,11916.8
|
| 146 |
+
2011,62,502.953953,173.237159,12468.3
|
| 147 |
+
"""
|
| 148 |
+
expected = read_csv(StringIO(csv_data), engine="python")
|
| 149 |
+
|
| 150 |
+
fwf_data = """\
|
| 151 |
+
A B C D E
|
| 152 |
+
201158 360.242940 149.910199 11950.7
|
| 153 |
+
201159 444.953632 166.985655 11788.4
|
| 154 |
+
201160 364.136849 183.628767 11806.2
|
| 155 |
+
201161 413.836124 184.375703 11916.8
|
| 156 |
+
201162 502.953953 173.237159 12468.3
|
| 157 |
+
"""
|
| 158 |
+
colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]
|
| 159 |
+
result = read_fwf(StringIO(fwf_data), colspecs=colspecs)
|
| 160 |
+
tm.assert_frame_equal(result, expected)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_bytes_io_input():
|
| 164 |
+
if not compat.PY3:
|
| 165 |
+
pytest.skip("Bytes-related test - only needs to work on Python 3")
|
| 166 |
+
|
| 167 |
+
result = read_fwf(BytesIO("שלום\nשלום".encode('utf8')),
|
| 168 |
+
widths=[2, 2], encoding="utf8")
|
| 169 |
+
expected = DataFrame([["של", "ום"]], columns=["של", "ום"])
|
| 170 |
+
tm.assert_frame_equal(result, expected)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_fwf_colspecs_is_list_or_tuple():
|
| 174 |
+
data = """index,A,B,C,D
|
| 175 |
+
foo,2,3,4,5
|
| 176 |
+
bar,7,8,9,10
|
| 177 |
+
baz,12,13,14,15
|
| 178 |
+
qux,12,13,14,15
|
| 179 |
+
foo2,12,13,14,15
|
| 180 |
+
bar2,12,13,14,15
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
msg = "column specifications must be a list or tuple.+"
|
| 184 |
+
|
| 185 |
+
with pytest.raises(TypeError, match=msg):
|
| 186 |
+
read_fwf(StringIO(data), colspecs={"a": 1}, delimiter=",")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples():
|
| 190 |
+
data = """index,A,B,C,D
|
| 191 |
+
foo,2,3,4,5
|
| 192 |
+
bar,7,8,9,10
|
| 193 |
+
baz,12,13,14,15
|
| 194 |
+
qux,12,13,14,15
|
| 195 |
+
foo2,12,13,14,15
|
| 196 |
+
bar2,12,13,14,15
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
msg = "Each column specification must be.+"
|
| 200 |
+
|
| 201 |
+
with pytest.raises(TypeError, match=msg):
|
| 202 |
+
read_fwf(StringIO(data), [("a", 1)])
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@pytest.mark.parametrize("colspecs,exp_data", [
|
| 206 |
+
([(0, 3), (3, None)], [[123, 456], [456, 789]]),
|
| 207 |
+
([(None, 3), (3, 6)], [[123, 456], [456, 789]]),
|
| 208 |
+
([(0, None), (3, None)], [[123456, 456], [456789, 789]]),
|
| 209 |
+
([(None, None), (3, 6)], [[123456, 456], [456789, 789]]),
|
| 210 |
+
])
|
| 211 |
+
def test_fwf_colspecs_none(colspecs, exp_data):
|
| 212 |
+
# see gh-7079
|
| 213 |
+
data = """\
|
| 214 |
+
123456
|
| 215 |
+
456789
|
| 216 |
+
"""
|
| 217 |
+
expected = DataFrame(exp_data)
|
| 218 |
+
|
| 219 |
+
result = read_fwf(StringIO(data), colspecs=colspecs, header=None)
|
| 220 |
+
tm.assert_frame_equal(result, expected)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize("infer_nrows,exp_data", [
|
| 224 |
+
# infer_nrows --> colspec == [(2, 3), (5, 6)]
|
| 225 |
+
(1, [[1, 2], [3, 8]]),
|
| 226 |
+
|
| 227 |
+
# infer_nrows > number of rows
|
| 228 |
+
(10, [[1, 2], [123, 98]]),
|
| 229 |
+
])
|
| 230 |
+
def test_fwf_colspecs_infer_nrows(infer_nrows, exp_data):
|
| 231 |
+
# see gh-15138
|
| 232 |
+
data = """\
|
| 233 |
+
1 2
|
| 234 |
+
123 98
|
| 235 |
+
"""
|
| 236 |
+
expected = DataFrame(exp_data)
|
| 237 |
+
|
| 238 |
+
result = read_fwf(StringIO(data), infer_nrows=infer_nrows, header=None)
|
| 239 |
+
tm.assert_frame_equal(result, expected)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_fwf_regression():
|
| 243 |
+
# see gh-3594
|
| 244 |
+
#
|
| 245 |
+
# Turns out "T060" is parsable as a datetime slice!
|
| 246 |
+
tz_list = [1, 10, 20, 30, 60, 80, 100]
|
| 247 |
+
widths = [16] + [8] * len(tz_list)
|
| 248 |
+
names = ["SST"] + ["T%03d" % z for z in tz_list[1:]]
|
| 249 |
+
|
| 250 |
+
data = """ 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192
|
| 251 |
+
2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869
|
| 252 |
+
2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657
|
| 253 |
+
2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379
|
| 254 |
+
2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039
|
| 255 |
+
"""
|
| 256 |
+
|
| 257 |
+
result = read_fwf(StringIO(data), index_col=0, header=None, names=names,
|
| 258 |
+
widths=widths, parse_dates=True,
|
| 259 |
+
date_parser=lambda s: datetime.strptime(s, "%Y%j%H%M%S"))
|
| 260 |
+
expected = DataFrame([
|
| 261 |
+
[9.5403, 9.4105, 8.6571, 7.8372, 6.0612, 5.8843, 5.5192],
|
| 262 |
+
[9.5435, 9.2010, 8.6167, 7.8176, 6.0804, 5.8728, 5.4869],
|
| 263 |
+
[9.5873, 9.1326, 8.4694, 7.5889, 6.0422, 5.8526, 5.4657],
|
| 264 |
+
[9.5810, 9.0896, 8.4009, 7.4652, 6.0322, 5.8189, 5.4379],
|
| 265 |
+
[9.6034, 9.0897, 8.3822, 7.4905, 6.0908, 5.7904, 5.4039],
|
| 266 |
+
], index=DatetimeIndex(["2009-06-13 20:20:00", "2009-06-13 20:30:00",
|
| 267 |
+
"2009-06-13 20:40:00", "2009-06-13 20:50:00",
|
| 268 |
+
"2009-06-13 21:00:00"]),
|
| 269 |
+
columns=["SST", "T010", "T020", "T030", "T060", "T080", "T100"])
|
| 270 |
+
tm.assert_frame_equal(result, expected)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_fwf_for_uint8():
|
| 274 |
+
data = """1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127
|
| 275 |
+
1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71""" # noqa
|
| 276 |
+
df = read_fwf(StringIO(data),
|
| 277 |
+
colspecs=[(0, 17), (25, 26), (33, 37),
|
| 278 |
+
(49, 51), (58, 62), (63, 1000)],
|
| 279 |
+
names=["time", "pri", "pgn", "dst", "src", "data"],
|
| 280 |
+
converters={
|
| 281 |
+
"pgn": lambda x: int(x, 16),
|
| 282 |
+
"src": lambda x: int(x, 16),
|
| 283 |
+
"dst": lambda x: int(x, 16),
|
| 284 |
+
"data": lambda x: len(x.split(" "))})
|
| 285 |
+
|
| 286 |
+
expected = DataFrame([[1421302965.213420, 3, 61184, 23, 40, 8],
|
| 287 |
+
[1421302964.226776, 6, 61442, None, 71, 8]],
|
| 288 |
+
columns=["time", "pri", "pgn",
|
| 289 |
+
"dst", "src", "data"])
|
| 290 |
+
expected["dst"] = expected["dst"].astype(object)
|
| 291 |
+
tm.assert_frame_equal(df, expected)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@pytest.mark.parametrize("comment", ["#", "~", "!"])
|
| 295 |
+
def test_fwf_comment(comment):
|
| 296 |
+
data = """\
|
| 297 |
+
1 2. 4 #hello world
|
| 298 |
+
5 NaN 10.0
|
| 299 |
+
"""
|
| 300 |
+
data = data.replace("#", comment)
|
| 301 |
+
|
| 302 |
+
colspecs = [(0, 3), (4, 9), (9, 25)]
|
| 303 |
+
expected = DataFrame([[1, 2., 4], [5, np.nan, 10.]])
|
| 304 |
+
|
| 305 |
+
result = read_fwf(StringIO(data), colspecs=colspecs,
|
| 306 |
+
header=None, comment=comment)
|
| 307 |
+
tm.assert_almost_equal(result, expected)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize("thousands", [",", "#", "~"])
|
| 311 |
+
def test_fwf_thousands(thousands):
|
| 312 |
+
data = """\
|
| 313 |
+
1 2,334.0 5
|
| 314 |
+
10 13 10.
|
| 315 |
+
"""
|
| 316 |
+
data = data.replace(",", thousands)
|
| 317 |
+
|
| 318 |
+
colspecs = [(0, 3), (3, 11), (12, 16)]
|
| 319 |
+
expected = DataFrame([[1, 2334., 5], [10, 13, 10.]])
|
| 320 |
+
|
| 321 |
+
result = read_fwf(StringIO(data), header=None,
|
| 322 |
+
colspecs=colspecs, thousands=thousands)
|
| 323 |
+
tm.assert_almost_equal(result, expected)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
@pytest.mark.parametrize("header", [True, False])
|
| 327 |
+
def test_bool_header_arg(header):
|
| 328 |
+
# see gh-6114
|
| 329 |
+
data = """\
|
| 330 |
+
MyColumn
|
| 331 |
+
a
|
| 332 |
+
b
|
| 333 |
+
a
|
| 334 |
+
b"""
|
| 335 |
+
|
| 336 |
+
msg = "Passing a bool to header is invalid"
|
| 337 |
+
with pytest.raises(TypeError, match=msg):
|
| 338 |
+
read_fwf(StringIO(data), header=header)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def test_full_file():
|
| 342 |
+
# File with all values.
|
| 343 |
+
test = """index A B C
|
| 344 |
+
2000-01-03T00:00:00 0.980268513777 3 foo
|
| 345 |
+
2000-01-04T00:00:00 1.04791624281 -4 bar
|
| 346 |
+
2000-01-05T00:00:00 0.498580885705 73 baz
|
| 347 |
+
2000-01-06T00:00:00 1.12020151869 1 foo
|
| 348 |
+
2000-01-07T00:00:00 0.487094399463 0 bar
|
| 349 |
+
2000-01-10T00:00:00 0.836648671666 2 baz
|
| 350 |
+
2000-01-11T00:00:00 0.157160753327 34 foo"""
|
| 351 |
+
colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))
|
| 352 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs)
|
| 353 |
+
|
| 354 |
+
result = read_fwf(StringIO(test))
|
| 355 |
+
tm.assert_frame_equal(result, expected)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def test_full_file_with_missing():
|
| 359 |
+
# File with missing values.
|
| 360 |
+
test = """index A B C
|
| 361 |
+
2000-01-03T00:00:00 0.980268513777 3 foo
|
| 362 |
+
2000-01-04T00:00:00 1.04791624281 -4 bar
|
| 363 |
+
0.498580885705 73 baz
|
| 364 |
+
2000-01-06T00:00:00 1.12020151869 1 foo
|
| 365 |
+
2000-01-07T00:00:00 0 bar
|
| 366 |
+
2000-01-10T00:00:00 0.836648671666 2 baz
|
| 367 |
+
34"""
|
| 368 |
+
colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))
|
| 369 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs)
|
| 370 |
+
|
| 371 |
+
result = read_fwf(StringIO(test))
|
| 372 |
+
tm.assert_frame_equal(result, expected)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_full_file_with_spaces():
|
| 376 |
+
# File with spaces in columns.
|
| 377 |
+
test = """
|
| 378 |
+
Account Name Balance CreditLimit AccountCreated
|
| 379 |
+
101 Keanu Reeves 9315.45 10000.00 1/17/1998
|
| 380 |
+
312 Gerard Butler 90.00 1000.00 8/6/2003
|
| 381 |
+
868 Jennifer Love Hewitt 0 17000.00 5/25/1985
|
| 382 |
+
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
|
| 383 |
+
317 Bill Murray 789.65 5000.00 2/5/2007
|
| 384 |
+
""".strip("\r\n")
|
| 385 |
+
colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))
|
| 386 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs)
|
| 387 |
+
|
| 388 |
+
result = read_fwf(StringIO(test))
|
| 389 |
+
tm.assert_frame_equal(result, expected)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def test_full_file_with_spaces_and_missing():
|
| 393 |
+
# File with spaces and missing values in columns.
|
| 394 |
+
test = """
|
| 395 |
+
Account Name Balance CreditLimit AccountCreated
|
| 396 |
+
101 10000.00 1/17/1998
|
| 397 |
+
312 Gerard Butler 90.00 1000.00 8/6/2003
|
| 398 |
+
868 5/25/1985
|
| 399 |
+
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
|
| 400 |
+
317 Bill Murray 789.65
|
| 401 |
+
""".strip("\r\n")
|
| 402 |
+
colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))
|
| 403 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs)
|
| 404 |
+
|
| 405 |
+
result = read_fwf(StringIO(test))
|
| 406 |
+
tm.assert_frame_equal(result, expected)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def test_messed_up_data():
|
| 410 |
+
# Completely messed up file.
|
| 411 |
+
test = """
|
| 412 |
+
Account Name Balance Credit Limit Account Created
|
| 413 |
+
101 10000.00 1/17/1998
|
| 414 |
+
312 Gerard Butler 90.00 1000.00
|
| 415 |
+
|
| 416 |
+
761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006
|
| 417 |
+
317 Bill Murray 789.65
|
| 418 |
+
""".strip("\r\n")
|
| 419 |
+
colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79))
|
| 420 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs)
|
| 421 |
+
|
| 422 |
+
result = read_fwf(StringIO(test))
|
| 423 |
+
tm.assert_frame_equal(result, expected)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def test_multiple_delimiters():
|
| 427 |
+
test = r"""
|
| 428 |
+
col1~~~~~col2 col3++++++++++++++++++col4
|
| 429 |
+
~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves
|
| 430 |
+
33+++122.33\\\bar.........Gerard Butler
|
| 431 |
+
++44~~~~12.01 baz~~Jennifer Love Hewitt
|
| 432 |
+
~~55 11+++foo++++Jada Pinkett-Smith
|
| 433 |
+
..66++++++.03~~~bar Bill Murray
|
| 434 |
+
""".strip("\r\n")
|
| 435 |
+
delimiter = " +~.\\"
|
| 436 |
+
colspecs = ((0, 4), (7, 13), (15, 19), (21, 41))
|
| 437 |
+
expected = read_fwf(StringIO(test), colspecs=colspecs, delimiter=delimiter)
|
| 438 |
+
|
| 439 |
+
result = read_fwf(StringIO(test), delimiter=delimiter)
|
| 440 |
+
tm.assert_frame_equal(result, expected)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def test_variable_width_unicode():
|
| 444 |
+
if not compat.PY3:
|
| 445 |
+
pytest.skip("Bytes-related test - only needs to work on Python 3")
|
| 446 |
+
|
| 447 |
+
data = """
|
| 448 |
+
שלום שלום
|
| 449 |
+
ום שלל
|
| 450 |
+
של ום
|
| 451 |
+
""".strip("\r\n")
|
| 452 |
+
encoding = "utf8"
|
| 453 |
+
kwargs = dict(header=None, encoding=encoding)
|
| 454 |
+
|
| 455 |
+
expected = read_fwf(BytesIO(data.encode(encoding)),
|
| 456 |
+
colspecs=[(0, 4), (5, 9)], **kwargs)
|
| 457 |
+
result = read_fwf(BytesIO(data.encode(encoding)), **kwargs)
|
| 458 |
+
tm.assert_frame_equal(result, expected)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
@pytest.mark.parametrize("dtype", [
|
| 462 |
+
dict(), {"a": "float64", "b": str, "c": "int32"}
|
| 463 |
+
])
|
| 464 |
+
def test_dtype(dtype):
|
| 465 |
+
data = """ a b c
|
| 466 |
+
1 2 3.2
|
| 467 |
+
3 4 5.2
|
| 468 |
+
"""
|
| 469 |
+
colspecs = [(0, 5), (5, 10), (10, None)]
|
| 470 |
+
result = read_fwf(StringIO(data), colspecs=colspecs, dtype=dtype)
|
| 471 |
+
|
| 472 |
+
expected = pd.DataFrame({
|
| 473 |
+
"a": [1, 3], "b": [2, 4],
|
| 474 |
+
"c": [3.2, 5.2]}, columns=["a", "b", "c"])
|
| 475 |
+
|
| 476 |
+
for col, dt in dtype.items():
|
| 477 |
+
expected[col] = expected[col].astype(dt)
|
| 478 |
+
|
| 479 |
+
tm.assert_frame_equal(result, expected)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def test_skiprows_inference():
|
| 483 |
+
# see gh-11256
|
| 484 |
+
data = """
|
| 485 |
+
Text contained in the file header
|
| 486 |
+
|
| 487 |
+
DataCol1 DataCol2
|
| 488 |
+
0.0 1.0
|
| 489 |
+
101.6 956.1
|
| 490 |
+
""".strip()
|
| 491 |
+
skiprows = 2
|
| 492 |
+
expected = read_csv(StringIO(data), skiprows=skiprows,
|
| 493 |
+
delim_whitespace=True)
|
| 494 |
+
|
| 495 |
+
result = read_fwf(StringIO(data), skiprows=skiprows)
|
| 496 |
+
tm.assert_frame_equal(result, expected)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def test_skiprows_by_index_inference():
|
| 500 |
+
data = """
|
| 501 |
+
To be skipped
|
| 502 |
+
Not To Be Skipped
|
| 503 |
+
Once more to be skipped
|
| 504 |
+
123 34 8 123
|
| 505 |
+
456 78 9 456
|
| 506 |
+
""".strip()
|
| 507 |
+
skiprows = [0, 2]
|
| 508 |
+
expected = read_csv(StringIO(data), skiprows=skiprows,
|
| 509 |
+
delim_whitespace=True)
|
| 510 |
+
|
| 511 |
+
result = read_fwf(StringIO(data), skiprows=skiprows)
|
| 512 |
+
tm.assert_frame_equal(result, expected)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def test_skiprows_inference_empty():
|
| 516 |
+
data = """
|
| 517 |
+
AA BBB C
|
| 518 |
+
12 345 6
|
| 519 |
+
78 901 2
|
| 520 |
+
""".strip()
|
| 521 |
+
|
| 522 |
+
msg = "No rows from which to infer column width"
|
| 523 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 524 |
+
read_fwf(StringIO(data), skiprows=3)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def test_whitespace_preservation():
|
| 528 |
+
# see gh-16772
|
| 529 |
+
header = None
|
| 530 |
+
csv_data = """
|
| 531 |
+
a ,bbb
|
| 532 |
+
cc,dd """
|
| 533 |
+
|
| 534 |
+
fwf_data = """
|
| 535 |
+
a bbb
|
| 536 |
+
ccdd """
|
| 537 |
+
result = read_fwf(StringIO(fwf_data), widths=[3, 3],
|
| 538 |
+
header=header, skiprows=[0], delimiter="\n\t")
|
| 539 |
+
expected = read_csv(StringIO(csv_data), header=header)
|
| 540 |
+
tm.assert_frame_equal(result, expected)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def test_default_delimiter():
|
| 544 |
+
header = None
|
| 545 |
+
csv_data = """
|
| 546 |
+
a,bbb
|
| 547 |
+
cc,dd"""
|
| 548 |
+
|
| 549 |
+
fwf_data = """
|
| 550 |
+
a \tbbb
|
| 551 |
+
cc\tdd """
|
| 552 |
+
result = read_fwf(StringIO(fwf_data), widths=[3, 3],
|
| 553 |
+
header=header, skiprows=[0])
|
| 554 |
+
expected = read_csv(StringIO(csv_data), header=header)
|
| 555 |
+
tm.assert_frame_equal(result, expected)
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
@pytest.mark.parametrize("infer", [True, False, None])
|
| 559 |
+
def test_fwf_compression(compression_only, infer):
|
| 560 |
+
data = """1111111111
|
| 561 |
+
2222222222
|
| 562 |
+
3333333333""".strip()
|
| 563 |
+
|
| 564 |
+
compression = compression_only
|
| 565 |
+
extension = "gz" if compression == "gzip" else compression
|
| 566 |
+
|
| 567 |
+
kwargs = dict(widths=[5, 5], names=["one", "two"])
|
| 568 |
+
expected = read_fwf(StringIO(data), **kwargs)
|
| 569 |
+
|
| 570 |
+
if compat.PY3:
|
| 571 |
+
data = bytes(data, encoding="utf-8")
|
| 572 |
+
|
| 573 |
+
with tm.ensure_clean(filename="tmp." + extension) as path:
|
| 574 |
+
tm.write_to_compressed(compression, path, data)
|
| 575 |
+
|
| 576 |
+
if infer is not None:
|
| 577 |
+
kwargs["compression"] = "infer" if infer else compression
|
| 578 |
+
|
| 579 |
+
result = read_fwf(path, **kwargs)
|
| 580 |
+
tm.assert_frame_equal(result, expected)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_skiprows.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests that skipped rows are properly handled during
|
| 5 |
+
parsing for all of the parsers defined in parsers.py
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from pandas.compat import StringIO, lrange, range
|
| 14 |
+
from pandas.errors import EmptyDataError
|
| 15 |
+
|
| 16 |
+
from pandas import DataFrame, Index
|
| 17 |
+
import pandas.util.testing as tm
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.mark.parametrize("skiprows", [lrange(6), 6])
|
| 21 |
+
def test_skip_rows_bug(all_parsers, skiprows):
|
| 22 |
+
# see gh-505
|
| 23 |
+
parser = all_parsers
|
| 24 |
+
text = """#foo,a,b,c
|
| 25 |
+
#foo,a,b,c
|
| 26 |
+
#foo,a,b,c
|
| 27 |
+
#foo,a,b,c
|
| 28 |
+
#foo,a,b,c
|
| 29 |
+
#foo,a,b,c
|
| 30 |
+
1/1/2000,1.,2.,3.
|
| 31 |
+
1/2/2000,4,5,6
|
| 32 |
+
1/3/2000,7,8,9
|
| 33 |
+
"""
|
| 34 |
+
result = parser.read_csv(StringIO(text), skiprows=skiprows, header=None,
|
| 35 |
+
index_col=0, parse_dates=True)
|
| 36 |
+
index = Index([datetime(2000, 1, 1), datetime(2000, 1, 2),
|
| 37 |
+
datetime(2000, 1, 3)], name=0)
|
| 38 |
+
|
| 39 |
+
expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
|
| 40 |
+
columns=[1, 2, 3], index=index)
|
| 41 |
+
tm.assert_frame_equal(result, expected)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_deep_skip_rows(all_parsers):
|
| 45 |
+
# see gh-4382
|
| 46 |
+
parser = all_parsers
|
| 47 |
+
data = "a,b,c\n" + "\n".join([",".join([str(i), str(i + 1), str(i + 2)])
|
| 48 |
+
for i in range(10)])
|
| 49 |
+
condensed_data = "a,b,c\n" + "\n".join([
|
| 50 |
+
",".join([str(i), str(i + 1), str(i + 2)])
|
| 51 |
+
for i in [0, 1, 2, 3, 4, 6, 8, 9]])
|
| 52 |
+
|
| 53 |
+
result = parser.read_csv(StringIO(data), skiprows=[6, 8])
|
| 54 |
+
condensed_result = parser.read_csv(StringIO(condensed_data))
|
| 55 |
+
tm.assert_frame_equal(result, condensed_result)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_skip_rows_blank(all_parsers):
|
| 59 |
+
# see gh-9832
|
| 60 |
+
parser = all_parsers
|
| 61 |
+
text = """#foo,a,b,c
|
| 62 |
+
#foo,a,b,c
|
| 63 |
+
|
| 64 |
+
#foo,a,b,c
|
| 65 |
+
#foo,a,b,c
|
| 66 |
+
|
| 67 |
+
1/1/2000,1.,2.,3.
|
| 68 |
+
1/2/2000,4,5,6
|
| 69 |
+
1/3/2000,7,8,9
|
| 70 |
+
"""
|
| 71 |
+
data = parser.read_csv(StringIO(text), skiprows=6, header=None,
|
| 72 |
+
index_col=0, parse_dates=True)
|
| 73 |
+
index = Index([datetime(2000, 1, 1), datetime(2000, 1, 2),
|
| 74 |
+
datetime(2000, 1, 3)], name=0)
|
| 75 |
+
|
| 76 |
+
expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
|
| 77 |
+
columns=[1, 2, 3],
|
| 78 |
+
index=index)
|
| 79 |
+
tm.assert_frame_equal(data, expected)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize("data,kwargs,expected", [
|
| 83 |
+
("""id,text,num_lines
|
| 84 |
+
1,"line 11
|
| 85 |
+
line 12",2
|
| 86 |
+
2,"line 21
|
| 87 |
+
line 22",2
|
| 88 |
+
3,"line 31",1""",
|
| 89 |
+
dict(skiprows=[1]),
|
| 90 |
+
DataFrame([[2, "line 21\nline 22", 2],
|
| 91 |
+
[3, "line 31", 1]], columns=["id", "text", "num_lines"])),
|
| 92 |
+
("a,b,c\n~a\n b~,~e\n d~,~f\n f~\n1,2,~12\n 13\n 14~",
|
| 93 |
+
dict(quotechar="~", skiprows=[2]),
|
| 94 |
+
DataFrame([["a\n b", "e\n d", "f\n f"]], columns=["a", "b", "c"])),
|
| 95 |
+
(("Text,url\n~example\n "
|
| 96 |
+
"sentence\n one~,url1\n~"
|
| 97 |
+
"example\n sentence\n two~,url2\n~"
|
| 98 |
+
"example\n sentence\n three~,url3"),
|
| 99 |
+
dict(quotechar="~", skiprows=[1, 3]),
|
| 100 |
+
DataFrame([['example\n sentence\n two', 'url2']],
|
| 101 |
+
columns=["Text", "url"]))
|
| 102 |
+
])
|
| 103 |
+
def test_skip_row_with_newline(all_parsers, data, kwargs, expected):
|
| 104 |
+
# see gh-12775 and gh-10911
|
| 105 |
+
parser = all_parsers
|
| 106 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 107 |
+
tm.assert_frame_equal(result, expected)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_skip_row_with_quote(all_parsers):
|
| 111 |
+
# see gh-12775 and gh-10911
|
| 112 |
+
parser = all_parsers
|
| 113 |
+
data = """id,text,num_lines
|
| 114 |
+
1,"line '11' line 12",2
|
| 115 |
+
2,"line '21' line 22",2
|
| 116 |
+
3,"line '31' line 32",1"""
|
| 117 |
+
|
| 118 |
+
exp_data = [[2, "line '21' line 22", 2],
|
| 119 |
+
[3, "line '31' line 32", 1]]
|
| 120 |
+
expected = DataFrame(exp_data, columns=[
|
| 121 |
+
"id", "text", "num_lines"])
|
| 122 |
+
|
| 123 |
+
result = parser.read_csv(StringIO(data), skiprows=[1])
|
| 124 |
+
tm.assert_frame_equal(result, expected)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@pytest.mark.parametrize("data,exp_data", [
|
| 128 |
+
("""id,text,num_lines
|
| 129 |
+
1,"line \n'11' line 12",2
|
| 130 |
+
2,"line \n'21' line 22",2
|
| 131 |
+
3,"line \n'31' line 32",1""",
|
| 132 |
+
[[2, "line \n'21' line 22", 2],
|
| 133 |
+
[3, "line \n'31' line 32", 1]]),
|
| 134 |
+
("""id,text,num_lines
|
| 135 |
+
1,"line '11\n' line 12",2
|
| 136 |
+
2,"line '21\n' line 22",2
|
| 137 |
+
3,"line '31\n' line 32",1""",
|
| 138 |
+
[[2, "line '21\n' line 22", 2],
|
| 139 |
+
[3, "line '31\n' line 32", 1]]),
|
| 140 |
+
("""id,text,num_lines
|
| 141 |
+
1,"line '11\n' \r\tline 12",2
|
| 142 |
+
2,"line '21\n' \r\tline 22",2
|
| 143 |
+
3,"line '31\n' \r\tline 32",1""",
|
| 144 |
+
[[2, "line '21\n' \r\tline 22", 2],
|
| 145 |
+
[3, "line '31\n' \r\tline 32", 1]]),
|
| 146 |
+
])
|
| 147 |
+
def test_skip_row_with_newline_and_quote(all_parsers, data, exp_data):
|
| 148 |
+
# see gh-12775 and gh-10911
|
| 149 |
+
parser = all_parsers
|
| 150 |
+
result = parser.read_csv(StringIO(data), skiprows=[1])
|
| 151 |
+
|
| 152 |
+
expected = DataFrame(exp_data, columns=["id", "text", "num_lines"])
|
| 153 |
+
tm.assert_frame_equal(result, expected)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("line_terminator", [
|
| 157 |
+
"\n", # "LF"
|
| 158 |
+
"\r\n", # "CRLF"
|
| 159 |
+
"\r" # "CR"
|
| 160 |
+
])
|
| 161 |
+
def test_skiprows_lineterminator(all_parsers, line_terminator):
|
| 162 |
+
# see gh-9079
|
| 163 |
+
parser = all_parsers
|
| 164 |
+
data = "\n".join(["SMOSMANIA ThetaProbe-ML2X ",
|
| 165 |
+
"2007/01/01 01:00 0.2140 U M ",
|
| 166 |
+
"2007/01/01 02:00 0.2141 M O ",
|
| 167 |
+
"2007/01/01 04:00 0.2142 D M "])
|
| 168 |
+
expected = DataFrame([["2007/01/01", "01:00", 0.2140, "U", "M"],
|
| 169 |
+
["2007/01/01", "02:00", 0.2141, "M", "O"],
|
| 170 |
+
["2007/01/01", "04:00", 0.2142, "D", "M"]],
|
| 171 |
+
columns=["date", "time", "var", "flag",
|
| 172 |
+
"oflag"])
|
| 173 |
+
|
| 174 |
+
if parser.engine == "python" and line_terminator == "\r":
|
| 175 |
+
pytest.skip("'CR' not respect with the Python parser yet")
|
| 176 |
+
|
| 177 |
+
data = data.replace("\n", line_terminator)
|
| 178 |
+
result = parser.read_csv(StringIO(data), skiprows=1, delim_whitespace=True,
|
| 179 |
+
names=["date", "time", "var", "flag", "oflag"])
|
| 180 |
+
tm.assert_frame_equal(result, expected)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_skiprows_infield_quote(all_parsers):
|
| 184 |
+
# see gh-14459
|
| 185 |
+
parser = all_parsers
|
| 186 |
+
data = "a\"\nb\"\na\n1"
|
| 187 |
+
expected = DataFrame({"a": [1]})
|
| 188 |
+
|
| 189 |
+
result = parser.read_csv(StringIO(data), skiprows=2)
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@pytest.mark.parametrize("kwargs,expected", [
|
| 194 |
+
(dict(), DataFrame({"1": [3, 5]})),
|
| 195 |
+
(dict(header=0, names=["foo"]), DataFrame({"foo": [3, 5]}))
|
| 196 |
+
])
|
| 197 |
+
def test_skip_rows_callable(all_parsers, kwargs, expected):
|
| 198 |
+
parser = all_parsers
|
| 199 |
+
data = "a\n1\n2\n3\n4\n5"
|
| 200 |
+
|
| 201 |
+
result = parser.read_csv(StringIO(data),
|
| 202 |
+
skiprows=lambda x: x % 2 == 0,
|
| 203 |
+
**kwargs)
|
| 204 |
+
tm.assert_frame_equal(result, expected)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_skip_rows_skip_all(all_parsers):
|
| 208 |
+
parser = all_parsers
|
| 209 |
+
data = "a\n1\n2\n3\n4\n5"
|
| 210 |
+
msg = "No columns to parse from file"
|
| 211 |
+
|
| 212 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 213 |
+
parser.read_csv(StringIO(data), skiprows=lambda x: True)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_skip_rows_bad_callable(all_parsers):
|
| 217 |
+
msg = "by zero"
|
| 218 |
+
parser = all_parsers
|
| 219 |
+
data = "a\n1\n2\n3\n4\n5"
|
| 220 |
+
|
| 221 |
+
with pytest.raises(ZeroDivisionError, match=msg):
|
| 222 |
+
parser.read_csv(StringIO(data), skiprows=lambda x: 1 / 0)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_textreader.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests the TextReader class in parsers.pyx, which
|
| 5 |
+
is integral to the C engine in parsers.py
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from numpy import nan
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
import pandas._libs.parsers as parser
|
| 15 |
+
from pandas._libs.parsers import TextReader
|
| 16 |
+
import pandas.compat as compat
|
| 17 |
+
from pandas.compat import BytesIO, StringIO, map
|
| 18 |
+
|
| 19 |
+
from pandas import DataFrame
|
| 20 |
+
import pandas.util.testing as tm
|
| 21 |
+
from pandas.util.testing import assert_frame_equal
|
| 22 |
+
|
| 23 |
+
from pandas.io.parsers import TextFileReader, read_csv
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestTextReader(object):
|
| 27 |
+
|
| 28 |
+
@pytest.fixture(autouse=True)
|
| 29 |
+
def setup_method(self, datapath):
|
| 30 |
+
self.dirpath = datapath('io', 'parser', 'data')
|
| 31 |
+
self.csv1 = os.path.join(self.dirpath, 'test1.csv')
|
| 32 |
+
self.csv2 = os.path.join(self.dirpath, 'test2.csv')
|
| 33 |
+
self.xls1 = os.path.join(self.dirpath, 'test.xls')
|
| 34 |
+
|
| 35 |
+
def test_file_handle(self):
|
| 36 |
+
with open(self.csv1, 'rb') as f:
|
| 37 |
+
reader = TextReader(f)
|
| 38 |
+
reader.read()
|
| 39 |
+
|
| 40 |
+
def test_string_filename(self):
|
| 41 |
+
reader = TextReader(self.csv1, header=None)
|
| 42 |
+
reader.read()
|
| 43 |
+
|
| 44 |
+
def test_file_handle_mmap(self):
|
| 45 |
+
with open(self.csv1, 'rb') as f:
|
| 46 |
+
reader = TextReader(f, memory_map=True, header=None)
|
| 47 |
+
reader.read()
|
| 48 |
+
|
| 49 |
+
def test_StringIO(self):
|
| 50 |
+
with open(self.csv1, 'rb') as f:
|
| 51 |
+
text = f.read()
|
| 52 |
+
src = BytesIO(text)
|
| 53 |
+
reader = TextReader(src, header=None)
|
| 54 |
+
reader.read()
|
| 55 |
+
|
| 56 |
+
def test_string_factorize(self):
|
| 57 |
+
# should this be optional?
|
| 58 |
+
data = 'a\nb\na\nb\na'
|
| 59 |
+
reader = TextReader(StringIO(data), header=None)
|
| 60 |
+
result = reader.read()
|
| 61 |
+
assert len(set(map(id, result[0]))) == 2
|
| 62 |
+
|
| 63 |
+
def test_skipinitialspace(self):
|
| 64 |
+
data = ('a, b\n'
|
| 65 |
+
'a, b\n'
|
| 66 |
+
'a, b\n'
|
| 67 |
+
'a, b')
|
| 68 |
+
|
| 69 |
+
reader = TextReader(StringIO(data), skipinitialspace=True,
|
| 70 |
+
header=None)
|
| 71 |
+
result = reader.read()
|
| 72 |
+
|
| 73 |
+
tm.assert_numpy_array_equal(result[0], np.array(['a', 'a', 'a', 'a'],
|
| 74 |
+
dtype=np.object_))
|
| 75 |
+
tm.assert_numpy_array_equal(result[1], np.array(['b', 'b', 'b', 'b'],
|
| 76 |
+
dtype=np.object_))
|
| 77 |
+
|
| 78 |
+
def test_parse_booleans(self):
|
| 79 |
+
data = 'True\nFalse\nTrue\nTrue'
|
| 80 |
+
|
| 81 |
+
reader = TextReader(StringIO(data), header=None)
|
| 82 |
+
result = reader.read()
|
| 83 |
+
|
| 84 |
+
assert result[0].dtype == np.bool_
|
| 85 |
+
|
| 86 |
+
def test_delimit_whitespace(self):
|
| 87 |
+
data = 'a b\na\t\t "b"\n"a"\t \t b'
|
| 88 |
+
|
| 89 |
+
reader = TextReader(StringIO(data), delim_whitespace=True,
|
| 90 |
+
header=None)
|
| 91 |
+
result = reader.read()
|
| 92 |
+
|
| 93 |
+
tm.assert_numpy_array_equal(result[0], np.array(['a', 'a', 'a'],
|
| 94 |
+
dtype=np.object_))
|
| 95 |
+
tm.assert_numpy_array_equal(result[1], np.array(['b', 'b', 'b'],
|
| 96 |
+
dtype=np.object_))
|
| 97 |
+
|
| 98 |
+
def test_embedded_newline(self):
|
| 99 |
+
data = 'a\n"hello\nthere"\nthis'
|
| 100 |
+
|
| 101 |
+
reader = TextReader(StringIO(data), header=None)
|
| 102 |
+
result = reader.read()
|
| 103 |
+
|
| 104 |
+
expected = np.array(['a', 'hello\nthere', 'this'], dtype=np.object_)
|
| 105 |
+
tm.assert_numpy_array_equal(result[0], expected)
|
| 106 |
+
|
| 107 |
+
def test_euro_decimal(self):
|
| 108 |
+
data = '12345,67\n345,678'
|
| 109 |
+
|
| 110 |
+
reader = TextReader(StringIO(data), delimiter=':',
|
| 111 |
+
decimal=',', header=None)
|
| 112 |
+
result = reader.read()
|
| 113 |
+
|
| 114 |
+
expected = np.array([12345.67, 345.678])
|
| 115 |
+
tm.assert_almost_equal(result[0], expected)
|
| 116 |
+
|
| 117 |
+
def test_integer_thousands(self):
|
| 118 |
+
data = '123,456\n12,500'
|
| 119 |
+
|
| 120 |
+
reader = TextReader(StringIO(data), delimiter=':',
|
| 121 |
+
thousands=',', header=None)
|
| 122 |
+
result = reader.read()
|
| 123 |
+
|
| 124 |
+
expected = np.array([123456, 12500], dtype=np.int64)
|
| 125 |
+
tm.assert_almost_equal(result[0], expected)
|
| 126 |
+
|
| 127 |
+
def test_integer_thousands_alt(self):
|
| 128 |
+
data = '123.456\n12.500'
|
| 129 |
+
|
| 130 |
+
reader = TextFileReader(StringIO(data), delimiter=':',
|
| 131 |
+
thousands='.', header=None)
|
| 132 |
+
result = reader.read()
|
| 133 |
+
|
| 134 |
+
expected = DataFrame([123456, 12500])
|
| 135 |
+
tm.assert_frame_equal(result, expected)
|
| 136 |
+
|
| 137 |
+
def test_skip_bad_lines(self, capsys):
|
| 138 |
+
# too many lines, see #2430 for why
|
| 139 |
+
data = ('a:b:c\n'
|
| 140 |
+
'd:e:f\n'
|
| 141 |
+
'g:h:i\n'
|
| 142 |
+
'j:k:l:m\n'
|
| 143 |
+
'l:m:n\n'
|
| 144 |
+
'o:p:q:r')
|
| 145 |
+
|
| 146 |
+
reader = TextReader(StringIO(data), delimiter=':',
|
| 147 |
+
header=None)
|
| 148 |
+
msg = (r"Error tokenizing data\. C error: Expected 3 fields in"
|
| 149 |
+
" line 4, saw 4")
|
| 150 |
+
with pytest.raises(parser.ParserError, match=msg):
|
| 151 |
+
reader.read()
|
| 152 |
+
|
| 153 |
+
reader = TextReader(StringIO(data), delimiter=':',
|
| 154 |
+
header=None,
|
| 155 |
+
error_bad_lines=False,
|
| 156 |
+
warn_bad_lines=False)
|
| 157 |
+
result = reader.read()
|
| 158 |
+
expected = {0: np.array(['a', 'd', 'g', 'l'], dtype=object),
|
| 159 |
+
1: np.array(['b', 'e', 'h', 'm'], dtype=object),
|
| 160 |
+
2: np.array(['c', 'f', 'i', 'n'], dtype=object)}
|
| 161 |
+
assert_array_dicts_equal(result, expected)
|
| 162 |
+
|
| 163 |
+
reader = TextReader(StringIO(data), delimiter=':',
|
| 164 |
+
header=None,
|
| 165 |
+
error_bad_lines=False,
|
| 166 |
+
warn_bad_lines=True)
|
| 167 |
+
reader.read()
|
| 168 |
+
captured = capsys.readouterr()
|
| 169 |
+
|
| 170 |
+
assert 'Skipping line 4' in captured.err
|
| 171 |
+
assert 'Skipping line 6' in captured.err
|
| 172 |
+
|
| 173 |
+
def test_header_not_enough_lines(self):
|
| 174 |
+
data = ('skip this\n'
|
| 175 |
+
'skip this\n'
|
| 176 |
+
'a,b,c\n'
|
| 177 |
+
'1,2,3\n'
|
| 178 |
+
'4,5,6')
|
| 179 |
+
|
| 180 |
+
reader = TextReader(StringIO(data), delimiter=',', header=2)
|
| 181 |
+
header = reader.header
|
| 182 |
+
expected = [['a', 'b', 'c']]
|
| 183 |
+
assert header == expected
|
| 184 |
+
|
| 185 |
+
recs = reader.read()
|
| 186 |
+
expected = {0: np.array([1, 4], dtype=np.int64),
|
| 187 |
+
1: np.array([2, 5], dtype=np.int64),
|
| 188 |
+
2: np.array([3, 6], dtype=np.int64)}
|
| 189 |
+
assert_array_dicts_equal(recs, expected)
|
| 190 |
+
|
| 191 |
+
def test_escapechar(self):
|
| 192 |
+
data = ('\\"hello world\"\n'
|
| 193 |
+
'\\"hello world\"\n'
|
| 194 |
+
'\\"hello world\"')
|
| 195 |
+
|
| 196 |
+
reader = TextReader(StringIO(data), delimiter=',', header=None,
|
| 197 |
+
escapechar='\\')
|
| 198 |
+
result = reader.read()
|
| 199 |
+
expected = {0: np.array(['"hello world"'] * 3, dtype=object)}
|
| 200 |
+
assert_array_dicts_equal(result, expected)
|
| 201 |
+
|
| 202 |
+
def test_eof_has_eol(self):
|
| 203 |
+
# handling of new line at EOF
|
| 204 |
+
pass
|
| 205 |
+
|
| 206 |
+
def test_na_substitution(self):
|
| 207 |
+
pass
|
| 208 |
+
|
| 209 |
+
def test_numpy_string_dtype(self):
|
| 210 |
+
data = """\
|
| 211 |
+
a,1
|
| 212 |
+
aa,2
|
| 213 |
+
aaa,3
|
| 214 |
+
aaaa,4
|
| 215 |
+
aaaaa,5"""
|
| 216 |
+
|
| 217 |
+
def _make_reader(**kwds):
|
| 218 |
+
return TextReader(StringIO(data), delimiter=',', header=None,
|
| 219 |
+
**kwds)
|
| 220 |
+
|
| 221 |
+
reader = _make_reader(dtype='S5,i4')
|
| 222 |
+
result = reader.read()
|
| 223 |
+
|
| 224 |
+
assert result[0].dtype == 'S5'
|
| 225 |
+
|
| 226 |
+
ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaaa'], dtype='S5')
|
| 227 |
+
assert (result[0] == ex_values).all()
|
| 228 |
+
assert result[1].dtype == 'i4'
|
| 229 |
+
|
| 230 |
+
reader = _make_reader(dtype='S4')
|
| 231 |
+
result = reader.read()
|
| 232 |
+
assert result[0].dtype == 'S4'
|
| 233 |
+
ex_values = np.array(['a', 'aa', 'aaa', 'aaaa', 'aaaa'], dtype='S4')
|
| 234 |
+
assert (result[0] == ex_values).all()
|
| 235 |
+
assert result[1].dtype == 'S4'
|
| 236 |
+
|
| 237 |
+
def test_pass_dtype(self):
|
| 238 |
+
data = """\
|
| 239 |
+
one,two
|
| 240 |
+
1,a
|
| 241 |
+
2,b
|
| 242 |
+
3,c
|
| 243 |
+
4,d"""
|
| 244 |
+
|
| 245 |
+
def _make_reader(**kwds):
|
| 246 |
+
return TextReader(StringIO(data), delimiter=',', **kwds)
|
| 247 |
+
|
| 248 |
+
reader = _make_reader(dtype={'one': 'u1', 1: 'S1'})
|
| 249 |
+
result = reader.read()
|
| 250 |
+
assert result[0].dtype == 'u1'
|
| 251 |
+
assert result[1].dtype == 'S1'
|
| 252 |
+
|
| 253 |
+
reader = _make_reader(dtype={'one': np.uint8, 1: object})
|
| 254 |
+
result = reader.read()
|
| 255 |
+
assert result[0].dtype == 'u1'
|
| 256 |
+
assert result[1].dtype == 'O'
|
| 257 |
+
|
| 258 |
+
reader = _make_reader(dtype={'one': np.dtype('u1'),
|
| 259 |
+
1: np.dtype('O')})
|
| 260 |
+
result = reader.read()
|
| 261 |
+
assert result[0].dtype == 'u1'
|
| 262 |
+
assert result[1].dtype == 'O'
|
| 263 |
+
|
| 264 |
+
def test_usecols(self):
|
| 265 |
+
data = """\
|
| 266 |
+
a,b,c
|
| 267 |
+
1,2,3
|
| 268 |
+
4,5,6
|
| 269 |
+
7,8,9
|
| 270 |
+
10,11,12"""
|
| 271 |
+
|
| 272 |
+
def _make_reader(**kwds):
|
| 273 |
+
return TextReader(StringIO(data), delimiter=',', **kwds)
|
| 274 |
+
|
| 275 |
+
reader = _make_reader(usecols=(1, 2))
|
| 276 |
+
result = reader.read()
|
| 277 |
+
|
| 278 |
+
exp = _make_reader().read()
|
| 279 |
+
assert len(result) == 2
|
| 280 |
+
assert (result[1] == exp[1]).all()
|
| 281 |
+
assert (result[2] == exp[2]).all()
|
| 282 |
+
|
| 283 |
+
def test_cr_delimited(self):
|
| 284 |
+
def _test(text, **kwargs):
|
| 285 |
+
nice_text = text.replace('\r', '\r\n')
|
| 286 |
+
result = TextReader(StringIO(text), **kwargs).read()
|
| 287 |
+
expected = TextReader(StringIO(nice_text), **kwargs).read()
|
| 288 |
+
assert_array_dicts_equal(result, expected)
|
| 289 |
+
|
| 290 |
+
data = 'a,b,c\r1,2,3\r4,5,6\r7,8,9\r10,11,12'
|
| 291 |
+
_test(data, delimiter=',')
|
| 292 |
+
|
| 293 |
+
data = 'a b c\r1 2 3\r4 5 6\r7 8 9\r10 11 12'
|
| 294 |
+
_test(data, delim_whitespace=True)
|
| 295 |
+
|
| 296 |
+
data = 'a,b,c\r1,2,3\r4,5,6\r,88,9\r10,11,12'
|
| 297 |
+
_test(data, delimiter=',')
|
| 298 |
+
|
| 299 |
+
sample = ('A,B,C,D,E,F,G,H,I,J,K,L,M,N,O\r'
|
| 300 |
+
'AAAAA,BBBBB,0,0,0,0,0,0,0,0,0,0,0,0,0\r'
|
| 301 |
+
',BBBBB,0,0,0,0,0,0,0,0,0,0,0,0,0')
|
| 302 |
+
_test(sample, delimiter=',')
|
| 303 |
+
|
| 304 |
+
data = 'A B C\r 2 3\r4 5 6'
|
| 305 |
+
_test(data, delim_whitespace=True)
|
| 306 |
+
|
| 307 |
+
data = 'A B C\r2 3\r4 5 6'
|
| 308 |
+
_test(data, delim_whitespace=True)
|
| 309 |
+
|
| 310 |
+
def test_empty_field_eof(self):
|
| 311 |
+
data = 'a,b,c\n1,2,3\n4,,'
|
| 312 |
+
|
| 313 |
+
result = TextReader(StringIO(data), delimiter=',').read()
|
| 314 |
+
|
| 315 |
+
expected = {0: np.array([1, 4], dtype=np.int64),
|
| 316 |
+
1: np.array(['2', ''], dtype=object),
|
| 317 |
+
2: np.array(['3', ''], dtype=object)}
|
| 318 |
+
assert_array_dicts_equal(result, expected)
|
| 319 |
+
|
| 320 |
+
# GH5664
|
| 321 |
+
a = DataFrame([['b'], [nan]], columns=['a'], index=['a', 'c'])
|
| 322 |
+
b = DataFrame([[1, 1, 1, 0], [1, 1, 1, 0]],
|
| 323 |
+
columns=list('abcd'),
|
| 324 |
+
index=[1, 1])
|
| 325 |
+
c = DataFrame([[1, 2, 3, 4], [6, nan, nan, nan],
|
| 326 |
+
[8, 9, 10, 11], [13, 14, nan, nan]],
|
| 327 |
+
columns=list('abcd'),
|
| 328 |
+
index=[0, 5, 7, 12])
|
| 329 |
+
|
| 330 |
+
for _ in range(100):
|
| 331 |
+
df = read_csv(StringIO('a,b\nc\n'), skiprows=0,
|
| 332 |
+
names=['a'], engine='c')
|
| 333 |
+
assert_frame_equal(df, a)
|
| 334 |
+
|
| 335 |
+
df = read_csv(StringIO('1,1,1,1,0\n' * 2 + '\n' * 2),
|
| 336 |
+
names=list("abcd"), engine='c')
|
| 337 |
+
assert_frame_equal(df, b)
|
| 338 |
+
|
| 339 |
+
df = read_csv(StringIO('0,1,2,3,4\n5,6\n7,8,9,10,11\n12,13,14'),
|
| 340 |
+
names=list('abcd'), engine='c')
|
| 341 |
+
assert_frame_equal(df, c)
|
| 342 |
+
|
| 343 |
+
def test_empty_csv_input(self):
|
| 344 |
+
# GH14867
|
| 345 |
+
df = read_csv(StringIO(), chunksize=20, header=None,
|
| 346 |
+
names=['a', 'b', 'c'])
|
| 347 |
+
assert isinstance(df, TextFileReader)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def assert_array_dicts_equal(left, right):
|
| 351 |
+
for k, v in compat.iteritems(left):
|
| 352 |
+
assert tm.assert_numpy_array_equal(np.asarray(v),
|
| 353 |
+
np.asarray(right[k]))
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_unsupported.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests that features that are currently unsupported in
|
| 5 |
+
either the Python or C parser are actually enforced
|
| 6 |
+
and are clearly communicated to the user.
|
| 7 |
+
|
| 8 |
+
Ultimately, the goal is to remove test cases from this
|
| 9 |
+
test suite as new feature support is added to the parsers.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
from pandas.compat import StringIO
|
| 15 |
+
from pandas.errors import ParserError
|
| 16 |
+
|
| 17 |
+
import pandas.util.testing as tm
|
| 18 |
+
|
| 19 |
+
import pandas.io.parsers as parsers
|
| 20 |
+
from pandas.io.parsers import read_csv
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.fixture(params=["python", "python-fwf"], ids=lambda val: val)
|
| 24 |
+
def python_engine(request):
|
| 25 |
+
return request.param
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestUnsupportedFeatures(object):
|
| 29 |
+
|
| 30 |
+
def test_mangle_dupe_cols_false(self):
|
| 31 |
+
# see gh-12935
|
| 32 |
+
data = 'a b c\n1 2 3'
|
| 33 |
+
msg = 'is not supported'
|
| 34 |
+
|
| 35 |
+
for engine in ('c', 'python'):
|
| 36 |
+
with pytest.raises(ValueError, match=msg):
|
| 37 |
+
read_csv(StringIO(data), engine=engine,
|
| 38 |
+
mangle_dupe_cols=False)
|
| 39 |
+
|
| 40 |
+
def test_c_engine(self):
|
| 41 |
+
# see gh-6607
|
| 42 |
+
data = 'a b c\n1 2 3'
|
| 43 |
+
msg = 'does not support'
|
| 44 |
+
|
| 45 |
+
# specify C engine with unsupported options (raise)
|
| 46 |
+
with pytest.raises(ValueError, match=msg):
|
| 47 |
+
read_csv(StringIO(data), engine='c',
|
| 48 |
+
sep=None, delim_whitespace=False)
|
| 49 |
+
with pytest.raises(ValueError, match=msg):
|
| 50 |
+
read_csv(StringIO(data), engine='c', sep=r'\s')
|
| 51 |
+
with pytest.raises(ValueError, match=msg):
|
| 52 |
+
read_csv(StringIO(data), engine='c', sep='\t', quotechar=chr(128))
|
| 53 |
+
with pytest.raises(ValueError, match=msg):
|
| 54 |
+
read_csv(StringIO(data), engine='c', skipfooter=1)
|
| 55 |
+
|
| 56 |
+
# specify C-unsupported options without python-unsupported options
|
| 57 |
+
with tm.assert_produces_warning(parsers.ParserWarning):
|
| 58 |
+
read_csv(StringIO(data), sep=None, delim_whitespace=False)
|
| 59 |
+
with tm.assert_produces_warning(parsers.ParserWarning):
|
| 60 |
+
read_csv(StringIO(data), sep=r'\s')
|
| 61 |
+
with tm.assert_produces_warning(parsers.ParserWarning):
|
| 62 |
+
read_csv(StringIO(data), sep='\t', quotechar=chr(128))
|
| 63 |
+
with tm.assert_produces_warning(parsers.ParserWarning):
|
| 64 |
+
read_csv(StringIO(data), skipfooter=1)
|
| 65 |
+
|
| 66 |
+
text = """ A B C D E
|
| 67 |
+
one two three four
|
| 68 |
+
a b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640
|
| 69 |
+
a q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744
|
| 70 |
+
x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838"""
|
| 71 |
+
msg = 'Error tokenizing data'
|
| 72 |
+
|
| 73 |
+
with pytest.raises(ParserError, match=msg):
|
| 74 |
+
read_csv(StringIO(text), sep='\\s+')
|
| 75 |
+
with pytest.raises(ParserError, match=msg):
|
| 76 |
+
read_csv(StringIO(text), engine='c', sep='\\s+')
|
| 77 |
+
|
| 78 |
+
msg = "Only length-1 thousands markers supported"
|
| 79 |
+
data = """A|B|C
|
| 80 |
+
1|2,334|5
|
| 81 |
+
10|13|10.
|
| 82 |
+
"""
|
| 83 |
+
with pytest.raises(ValueError, match=msg):
|
| 84 |
+
read_csv(StringIO(data), thousands=',,')
|
| 85 |
+
with pytest.raises(ValueError, match=msg):
|
| 86 |
+
read_csv(StringIO(data), thousands='')
|
| 87 |
+
|
| 88 |
+
msg = "Only length-1 line terminators supported"
|
| 89 |
+
data = 'a,b,c~~1,2,3~~4,5,6'
|
| 90 |
+
with pytest.raises(ValueError, match=msg):
|
| 91 |
+
read_csv(StringIO(data), lineterminator='~~')
|
| 92 |
+
|
| 93 |
+
def test_python_engine(self, python_engine):
|
| 94 |
+
from pandas.io.parsers import _python_unsupported as py_unsupported
|
| 95 |
+
|
| 96 |
+
data = """1,2,3,,
|
| 97 |
+
1,2,3,4,
|
| 98 |
+
1,2,3,4,5
|
| 99 |
+
1,2,,,
|
| 100 |
+
1,2,3,4,"""
|
| 101 |
+
|
| 102 |
+
for default in py_unsupported:
|
| 103 |
+
msg = ('The %r option is not supported '
|
| 104 |
+
'with the %r engine' % (default, python_engine))
|
| 105 |
+
|
| 106 |
+
kwargs = {default: object()}
|
| 107 |
+
with pytest.raises(ValueError, match=msg):
|
| 108 |
+
read_csv(StringIO(data), engine=python_engine, **kwargs)
|
| 109 |
+
|
| 110 |
+
def test_python_engine_file_no_next(self, python_engine):
|
| 111 |
+
# see gh-16530
|
| 112 |
+
class NoNextBuffer(object):
|
| 113 |
+
def __init__(self, csv_data):
|
| 114 |
+
self.data = csv_data
|
| 115 |
+
|
| 116 |
+
def __iter__(self):
|
| 117 |
+
return self
|
| 118 |
+
|
| 119 |
+
def read(self):
|
| 120 |
+
return self.data
|
| 121 |
+
|
| 122 |
+
data = "a\n1"
|
| 123 |
+
msg = "The 'python' engine cannot iterate"
|
| 124 |
+
|
| 125 |
+
with pytest.raises(ValueError, match=msg):
|
| 126 |
+
read_csv(NoNextBuffer(data), engine=python_engine)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TestDeprecatedFeatures(object):
|
| 130 |
+
|
| 131 |
+
@pytest.mark.parametrize("engine", ["c", "python"])
|
| 132 |
+
@pytest.mark.parametrize("kwargs", [{"tupleize_cols": True},
|
| 133 |
+
{"tupleize_cols": False}])
|
| 134 |
+
def test_deprecated_args(self, engine, kwargs):
|
| 135 |
+
data = "1,2,3"
|
| 136 |
+
arg, _ = list(kwargs.items())[0]
|
| 137 |
+
|
| 138 |
+
with tm.assert_produces_warning(
|
| 139 |
+
FutureWarning, check_stacklevel=False):
|
| 140 |
+
read_csv(StringIO(data), engine=engine, **kwargs)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/io/parser/test_usecols.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Tests the usecols functionality during parsing
|
| 5 |
+
for all of the parsers defined in parsers.py
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas._libs.tslib import Timestamp
|
| 12 |
+
from pandas.compat import StringIO
|
| 13 |
+
|
| 14 |
+
from pandas import DataFrame, Index
|
| 15 |
+
import pandas.util.testing as tm
|
| 16 |
+
|
| 17 |
+
_msg_validate_usecols_arg = ("'usecols' must either be list-like "
|
| 18 |
+
"of all strings, all unicode, all "
|
| 19 |
+
"integers or a callable.")
|
| 20 |
+
_msg_validate_usecols_names = ("Usecols do not match columns, columns "
|
| 21 |
+
"expected but not found: {0}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_raise_on_mixed_dtype_usecols(all_parsers):
|
| 25 |
+
# See gh-12678
|
| 26 |
+
data = """a,b,c
|
| 27 |
+
1000,2000,3000
|
| 28 |
+
4000,5000,6000
|
| 29 |
+
"""
|
| 30 |
+
usecols = [0, "b", 2]
|
| 31 |
+
parser = all_parsers
|
| 32 |
+
|
| 33 |
+
with pytest.raises(ValueError, match=_msg_validate_usecols_arg):
|
| 34 |
+
parser.read_csv(StringIO(data), usecols=usecols)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize("usecols", [(1, 2), ("b", "c")])
|
| 38 |
+
def test_usecols(all_parsers, usecols):
|
| 39 |
+
data = """\
|
| 40 |
+
a,b,c
|
| 41 |
+
1,2,3
|
| 42 |
+
4,5,6
|
| 43 |
+
7,8,9
|
| 44 |
+
10,11,12"""
|
| 45 |
+
parser = all_parsers
|
| 46 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 47 |
+
|
| 48 |
+
expected = DataFrame([[2, 3], [5, 6], [8, 9],
|
| 49 |
+
[11, 12]], columns=["b", "c"])
|
| 50 |
+
tm.assert_frame_equal(result, expected)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_usecols_with_names(all_parsers):
|
| 54 |
+
data = """\
|
| 55 |
+
a,b,c
|
| 56 |
+
1,2,3
|
| 57 |
+
4,5,6
|
| 58 |
+
7,8,9
|
| 59 |
+
10,11,12"""
|
| 60 |
+
parser = all_parsers
|
| 61 |
+
names = ["foo", "bar"]
|
| 62 |
+
result = parser.read_csv(StringIO(data), names=names,
|
| 63 |
+
usecols=[1, 2], header=0)
|
| 64 |
+
|
| 65 |
+
expected = DataFrame([[2, 3], [5, 6], [8, 9],
|
| 66 |
+
[11, 12]], columns=names)
|
| 67 |
+
tm.assert_frame_equal(result, expected)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.mark.parametrize("names,usecols", [
|
| 71 |
+
(["b", "c"], [1, 2]),
|
| 72 |
+
(["a", "b", "c"], ["b", "c"])
|
| 73 |
+
])
|
| 74 |
+
def test_usecols_relative_to_names(all_parsers, names, usecols):
|
| 75 |
+
data = """\
|
| 76 |
+
1,2,3
|
| 77 |
+
4,5,6
|
| 78 |
+
7,8,9
|
| 79 |
+
10,11,12"""
|
| 80 |
+
parser = all_parsers
|
| 81 |
+
result = parser.read_csv(StringIO(data), names=names,
|
| 82 |
+
header=None, usecols=usecols)
|
| 83 |
+
|
| 84 |
+
expected = DataFrame([[2, 3], [5, 6], [8, 9],
|
| 85 |
+
[11, 12]], columns=["b", "c"])
|
| 86 |
+
tm.assert_frame_equal(result, expected)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_usecols_relative_to_names2(all_parsers):
|
| 90 |
+
# see gh-5766
|
| 91 |
+
data = """\
|
| 92 |
+
1,2,3
|
| 93 |
+
4,5,6
|
| 94 |
+
7,8,9
|
| 95 |
+
10,11,12"""
|
| 96 |
+
parser = all_parsers
|
| 97 |
+
result = parser.read_csv(StringIO(data), names=["a", "b"],
|
| 98 |
+
header=None, usecols=[0, 1])
|
| 99 |
+
|
| 100 |
+
expected = DataFrame([[1, 2], [4, 5], [7, 8],
|
| 101 |
+
[10, 11]], columns=["a", "b"])
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_usecols_name_length_conflict(all_parsers):
|
| 106 |
+
data = """\
|
| 107 |
+
1,2,3
|
| 108 |
+
4,5,6
|
| 109 |
+
7,8,9
|
| 110 |
+
10,11,12"""
|
| 111 |
+
parser = all_parsers
|
| 112 |
+
msg = ("Number of passed names did not "
|
| 113 |
+
"match number of header fields in the file"
|
| 114 |
+
if parser.engine == "python" else
|
| 115 |
+
"Passed header names mismatches usecols")
|
| 116 |
+
|
| 117 |
+
with pytest.raises(ValueError, match=msg):
|
| 118 |
+
parser.read_csv(StringIO(data), names=["a", "b"],
|
| 119 |
+
header=None, usecols=[1])
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_usecols_single_string(all_parsers):
|
| 123 |
+
# see gh-20558
|
| 124 |
+
parser = all_parsers
|
| 125 |
+
data = """foo, bar, baz
|
| 126 |
+
1000, 2000, 3000
|
| 127 |
+
4000, 5000, 6000"""
|
| 128 |
+
|
| 129 |
+
with pytest.raises(ValueError, match=_msg_validate_usecols_arg):
|
| 130 |
+
parser.read_csv(StringIO(data), usecols="foo")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@pytest.mark.parametrize("data", ["a,b,c,d\n1,2,3,4\n5,6,7,8",
|
| 134 |
+
"a,b,c,d\n1,2,3,4,\n5,6,7,8,"])
|
| 135 |
+
def test_usecols_index_col_false(all_parsers, data):
|
| 136 |
+
# see gh-9082
|
| 137 |
+
parser = all_parsers
|
| 138 |
+
usecols = ["a", "c", "d"]
|
| 139 |
+
expected = DataFrame({"a": [1, 5], "c": [3, 7], "d": [4, 8]})
|
| 140 |
+
|
| 141 |
+
result = parser.read_csv(StringIO(data), usecols=usecols, index_col=False)
|
| 142 |
+
tm.assert_frame_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@pytest.mark.parametrize("index_col", ["b", 0])
|
| 146 |
+
@pytest.mark.parametrize("usecols", [["b", "c"], [1, 2]])
|
| 147 |
+
def test_usecols_index_col_conflict(all_parsers, usecols, index_col):
|
| 148 |
+
# see gh-4201: test that index_col as integer reflects usecols
|
| 149 |
+
parser = all_parsers
|
| 150 |
+
data = "a,b,c,d\nA,a,1,one\nB,b,2,two"
|
| 151 |
+
expected = DataFrame({"c": [1, 2]}, index=Index(["a", "b"], name="b"))
|
| 152 |
+
|
| 153 |
+
result = parser.read_csv(StringIO(data), usecols=usecols,
|
| 154 |
+
index_col=index_col)
|
| 155 |
+
tm.assert_frame_equal(result, expected)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_usecols_index_col_conflict2(all_parsers):
|
| 159 |
+
# see gh-4201: test that index_col as integer reflects usecols
|
| 160 |
+
parser = all_parsers
|
| 161 |
+
data = "a,b,c,d\nA,a,1,one\nB,b,2,two"
|
| 162 |
+
|
| 163 |
+
expected = DataFrame({"b": ["a", "b"], "c": [1, 2], "d": ("one", "two")})
|
| 164 |
+
expected = expected.set_index(["b", "c"])
|
| 165 |
+
|
| 166 |
+
result = parser.read_csv(StringIO(data), usecols=["b", "c", "d"],
|
| 167 |
+
index_col=["b", "c"])
|
| 168 |
+
tm.assert_frame_equal(result, expected)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def test_usecols_implicit_index_col(all_parsers):
|
| 172 |
+
# see gh-2654
|
| 173 |
+
parser = all_parsers
|
| 174 |
+
data = "a,b,c\n4,apple,bat,5.7\n8,orange,cow,10"
|
| 175 |
+
|
| 176 |
+
result = parser.read_csv(StringIO(data), usecols=["a", "b"])
|
| 177 |
+
expected = DataFrame({"a": ["apple", "orange"],
|
| 178 |
+
"b": ["bat", "cow"]}, index=[4, 8])
|
| 179 |
+
tm.assert_frame_equal(result, expected)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_usecols_regex_sep(all_parsers):
|
| 183 |
+
# see gh-2733
|
| 184 |
+
parser = all_parsers
|
| 185 |
+
data = "a b c\n4 apple bat 5.7\n8 orange cow 10"
|
| 186 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+", usecols=("a", "b"))
|
| 187 |
+
|
| 188 |
+
expected = DataFrame({"a": ["apple", "orange"],
|
| 189 |
+
"b": ["bat", "cow"]}, index=[4, 8])
|
| 190 |
+
tm.assert_frame_equal(result, expected)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_usecols_with_whitespace(all_parsers):
|
| 194 |
+
parser = all_parsers
|
| 195 |
+
data = "a b c\n4 apple bat 5.7\n8 orange cow 10"
|
| 196 |
+
|
| 197 |
+
result = parser.read_csv(StringIO(data), delim_whitespace=True,
|
| 198 |
+
usecols=("a", "b"))
|
| 199 |
+
expected = DataFrame({"a": ["apple", "orange"],
|
| 200 |
+
"b": ["bat", "cow"]}, index=[4, 8])
|
| 201 |
+
tm.assert_frame_equal(result, expected)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@pytest.mark.parametrize("usecols,expected", [
|
| 205 |
+
# Column selection by index.
|
| 206 |
+
([0, 1], DataFrame(data=[[1000, 2000], [4000, 5000]],
|
| 207 |
+
columns=["2", "0"])),
|
| 208 |
+
|
| 209 |
+
# Column selection by name.
|
| 210 |
+
(["0", "1"], DataFrame(data=[[2000, 3000], [5000, 6000]],
|
| 211 |
+
columns=["0", "1"])),
|
| 212 |
+
])
|
| 213 |
+
def test_usecols_with_integer_like_header(all_parsers, usecols, expected):
|
| 214 |
+
parser = all_parsers
|
| 215 |
+
data = """2,0,1
|
| 216 |
+
1000,2000,3000
|
| 217 |
+
4000,5000,6000"""
|
| 218 |
+
|
| 219 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 220 |
+
tm.assert_frame_equal(result, expected)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]])
|
| 224 |
+
def test_usecols_with_parse_dates(all_parsers, usecols):
|
| 225 |
+
# see gh-9755
|
| 226 |
+
data = """a,b,c,d,e
|
| 227 |
+
0,1,20140101,0900,4
|
| 228 |
+
0,1,20140102,1000,4"""
|
| 229 |
+
parser = all_parsers
|
| 230 |
+
parse_dates = [[1, 2]]
|
| 231 |
+
|
| 232 |
+
cols = {
|
| 233 |
+
"a": [0, 0],
|
| 234 |
+
"c_d": [
|
| 235 |
+
Timestamp("2014-01-01 09:00:00"),
|
| 236 |
+
Timestamp("2014-01-02 10:00:00")
|
| 237 |
+
]
|
| 238 |
+
}
|
| 239 |
+
expected = DataFrame(cols, columns=["c_d", "a"])
|
| 240 |
+
result = parser.read_csv(StringIO(data), usecols=usecols,
|
| 241 |
+
parse_dates=parse_dates)
|
| 242 |
+
tm.assert_frame_equal(result, expected)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_usecols_with_parse_dates2(all_parsers):
|
| 246 |
+
# see gh-13604
|
| 247 |
+
parser = all_parsers
|
| 248 |
+
data = """2008-02-07 09:40,1032.43
|
| 249 |
+
2008-02-07 09:50,1042.54
|
| 250 |
+
2008-02-07 10:00,1051.65"""
|
| 251 |
+
|
| 252 |
+
names = ["date", "values"]
|
| 253 |
+
usecols = names[:]
|
| 254 |
+
parse_dates = [0]
|
| 255 |
+
|
| 256 |
+
index = Index([Timestamp("2008-02-07 09:40"),
|
| 257 |
+
Timestamp("2008-02-07 09:50"),
|
| 258 |
+
Timestamp("2008-02-07 10:00")],
|
| 259 |
+
name="date")
|
| 260 |
+
cols = {"values": [1032.43, 1042.54, 1051.65]}
|
| 261 |
+
expected = DataFrame(cols, index=index)
|
| 262 |
+
|
| 263 |
+
result = parser.read_csv(StringIO(data), parse_dates=parse_dates,
|
| 264 |
+
index_col=0, usecols=usecols,
|
| 265 |
+
header=None, names=names)
|
| 266 |
+
tm.assert_frame_equal(result, expected)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def test_usecols_with_parse_dates3(all_parsers):
|
| 270 |
+
# see gh-14792
|
| 271 |
+
parser = all_parsers
|
| 272 |
+
data = """a,b,c,d,e,f,g,h,i,j
|
| 273 |
+
2016/09/21,1,1,2,3,4,5,6,7,8"""
|
| 274 |
+
|
| 275 |
+
usecols = list("abcdefghij")
|
| 276 |
+
parse_dates = [0]
|
| 277 |
+
|
| 278 |
+
cols = {"a": Timestamp("2016-09-21"),
|
| 279 |
+
"b": [1], "c": [1], "d": [2],
|
| 280 |
+
"e": [3], "f": [4], "g": [5],
|
| 281 |
+
"h": [6], "i": [7], "j": [8]}
|
| 282 |
+
expected = DataFrame(cols, columns=usecols)
|
| 283 |
+
|
| 284 |
+
result = parser.read_csv(StringIO(data), usecols=usecols,
|
| 285 |
+
parse_dates=parse_dates)
|
| 286 |
+
tm.assert_frame_equal(result, expected)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def test_usecols_with_parse_dates4(all_parsers):
|
| 290 |
+
data = "a,b,c,d,e,f,g,h,i,j\n2016/09/21,1,1,2,3,4,5,6,7,8"
|
| 291 |
+
usecols = list("abcdefghij")
|
| 292 |
+
parse_dates = [[0, 1]]
|
| 293 |
+
parser = all_parsers
|
| 294 |
+
|
| 295 |
+
cols = {"a_b": "2016/09/21 1",
|
| 296 |
+
"c": [1], "d": [2], "e": [3], "f": [4],
|
| 297 |
+
"g": [5], "h": [6], "i": [7], "j": [8]}
|
| 298 |
+
expected = DataFrame(cols, columns=["a_b"] + list("cdefghij"))
|
| 299 |
+
|
| 300 |
+
result = parser.read_csv(StringIO(data), usecols=usecols,
|
| 301 |
+
parse_dates=parse_dates)
|
| 302 |
+
tm.assert_frame_equal(result, expected)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]])
|
| 306 |
+
@pytest.mark.parametrize("names", [
|
| 307 |
+
list("abcde"), # Names span all columns in original data.
|
| 308 |
+
list("acd"), # Names span only the selected columns.
|
| 309 |
+
])
|
| 310 |
+
def test_usecols_with_parse_dates_and_names(all_parsers, usecols, names):
|
| 311 |
+
# see gh-9755
|
| 312 |
+
s = """0,1,20140101,0900,4
|
| 313 |
+
0,1,20140102,1000,4"""
|
| 314 |
+
parse_dates = [[1, 2]]
|
| 315 |
+
parser = all_parsers
|
| 316 |
+
|
| 317 |
+
cols = {
|
| 318 |
+
"a": [0, 0],
|
| 319 |
+
"c_d": [
|
| 320 |
+
Timestamp("2014-01-01 09:00:00"),
|
| 321 |
+
Timestamp("2014-01-02 10:00:00")
|
| 322 |
+
]
|
| 323 |
+
}
|
| 324 |
+
expected = DataFrame(cols, columns=["c_d", "a"])
|
| 325 |
+
|
| 326 |
+
result = parser.read_csv(StringIO(s), names=names,
|
| 327 |
+
parse_dates=parse_dates,
|
| 328 |
+
usecols=usecols)
|
| 329 |
+
tm.assert_frame_equal(result, expected)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def test_usecols_with_unicode_strings(all_parsers):
|
| 333 |
+
# see gh-13219
|
| 334 |
+
data = """AAA,BBB,CCC,DDD
|
| 335 |
+
0.056674973,8,True,a
|
| 336 |
+
2.613230982,2,False,b
|
| 337 |
+
3.568935038,7,False,a"""
|
| 338 |
+
parser = all_parsers
|
| 339 |
+
|
| 340 |
+
exp_data = {
|
| 341 |
+
"AAA": {
|
| 342 |
+
0: 0.056674972999999997,
|
| 343 |
+
1: 2.6132309819999997,
|
| 344 |
+
2: 3.5689350380000002
|
| 345 |
+
},
|
| 346 |
+
"BBB": {0: 8, 1: 2, 2: 7}
|
| 347 |
+
}
|
| 348 |
+
expected = DataFrame(exp_data)
|
| 349 |
+
|
| 350 |
+
result = parser.read_csv(StringIO(data), usecols=[u"AAA", u"BBB"])
|
| 351 |
+
tm.assert_frame_equal(result, expected)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_usecols_with_single_byte_unicode_strings(all_parsers):
|
| 355 |
+
# see gh-13219
|
| 356 |
+
data = """A,B,C,D
|
| 357 |
+
0.056674973,8,True,a
|
| 358 |
+
2.613230982,2,False,b
|
| 359 |
+
3.568935038,7,False,a"""
|
| 360 |
+
parser = all_parsers
|
| 361 |
+
|
| 362 |
+
exp_data = {
|
| 363 |
+
"A": {
|
| 364 |
+
0: 0.056674972999999997,
|
| 365 |
+
1: 2.6132309819999997,
|
| 366 |
+
2: 3.5689350380000002
|
| 367 |
+
},
|
| 368 |
+
"B": {0: 8, 1: 2, 2: 7}
|
| 369 |
+
}
|
| 370 |
+
expected = DataFrame(exp_data)
|
| 371 |
+
|
| 372 |
+
result = parser.read_csv(StringIO(data), usecols=[u"A", u"B"])
|
| 373 |
+
tm.assert_frame_equal(result, expected)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@pytest.mark.parametrize("usecols", [[u"AAA", b"BBB"], [b"AAA", u"BBB"]])
|
| 377 |
+
def test_usecols_with_mixed_encoding_strings(all_parsers, usecols):
|
| 378 |
+
data = """AAA,BBB,CCC,DDD
|
| 379 |
+
0.056674973,8,True,a
|
| 380 |
+
2.613230982,2,False,b
|
| 381 |
+
3.568935038,7,False,a"""
|
| 382 |
+
parser = all_parsers
|
| 383 |
+
|
| 384 |
+
with pytest.raises(ValueError, match=_msg_validate_usecols_arg):
|
| 385 |
+
parser.read_csv(StringIO(data), usecols=usecols)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@pytest.mark.parametrize("usecols", [
|
| 389 |
+
["あああ", "いい"],
|
| 390 |
+
[u"あああ", u"いい"]
|
| 391 |
+
])
|
| 392 |
+
def test_usecols_with_multi_byte_characters(all_parsers, usecols):
|
| 393 |
+
data = """あああ,いい,ううう,ええええ
|
| 394 |
+
0.056674973,8,True,a
|
| 395 |
+
2.613230982,2,False,b
|
| 396 |
+
3.568935038,7,False,a"""
|
| 397 |
+
parser = all_parsers
|
| 398 |
+
|
| 399 |
+
exp_data = {
|
| 400 |
+
"あああ": {
|
| 401 |
+
0: 0.056674972999999997,
|
| 402 |
+
1: 2.6132309819999997,
|
| 403 |
+
2: 3.5689350380000002
|
| 404 |
+
},
|
| 405 |
+
"いい": {0: 8, 1: 2, 2: 7}
|
| 406 |
+
}
|
| 407 |
+
expected = DataFrame(exp_data)
|
| 408 |
+
|
| 409 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 410 |
+
tm.assert_frame_equal(result, expected)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_empty_usecols(all_parsers):
|
| 414 |
+
data = "a,b,c\n1,2,3\n4,5,6"
|
| 415 |
+
expected = DataFrame()
|
| 416 |
+
parser = all_parsers
|
| 417 |
+
|
| 418 |
+
result = parser.read_csv(StringIO(data), usecols=set())
|
| 419 |
+
tm.assert_frame_equal(result, expected)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def test_np_array_usecols(all_parsers):
|
| 423 |
+
# see gh-12546
|
| 424 |
+
parser = all_parsers
|
| 425 |
+
data = "a,b,c\n1,2,3"
|
| 426 |
+
usecols = np.array(["a", "b"])
|
| 427 |
+
|
| 428 |
+
expected = DataFrame([[1, 2]], columns=usecols)
|
| 429 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 430 |
+
tm.assert_frame_equal(result, expected)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@pytest.mark.parametrize("usecols,expected", [
|
| 434 |
+
(lambda x: x.upper() in ["AAA", "BBB", "DDD"],
|
| 435 |
+
DataFrame({
|
| 436 |
+
"AaA": {
|
| 437 |
+
0: 0.056674972999999997,
|
| 438 |
+
1: 2.6132309819999997,
|
| 439 |
+
2: 3.5689350380000002
|
| 440 |
+
},
|
| 441 |
+
"bBb": {0: 8, 1: 2, 2: 7},
|
| 442 |
+
"ddd": {0: "a", 1: "b", 2: "a"}
|
| 443 |
+
})),
|
| 444 |
+
(lambda x: False, DataFrame()),
|
| 445 |
+
])
|
| 446 |
+
def test_callable_usecols(all_parsers, usecols, expected):
|
| 447 |
+
# see gh-14154
|
| 448 |
+
data = """AaA,bBb,CCC,ddd
|
| 449 |
+
0.056674973,8,True,a
|
| 450 |
+
2.613230982,2,False,b
|
| 451 |
+
3.568935038,7,False,a"""
|
| 452 |
+
parser = all_parsers
|
| 453 |
+
|
| 454 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 455 |
+
tm.assert_frame_equal(result, expected)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
@pytest.mark.parametrize("usecols", [["a", "c"], lambda x: x in ["a", "c"]])
|
| 459 |
+
def test_incomplete_first_row(all_parsers, usecols):
|
| 460 |
+
# see gh-6710
|
| 461 |
+
data = "1,2\n1,2,3"
|
| 462 |
+
parser = all_parsers
|
| 463 |
+
names = ["a", "b", "c"]
|
| 464 |
+
expected = DataFrame({"a": [1, 1], "c": [np.nan, 3]})
|
| 465 |
+
|
| 466 |
+
result = parser.read_csv(StringIO(data), names=names, usecols=usecols)
|
| 467 |
+
tm.assert_frame_equal(result, expected)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
@pytest.mark.parametrize("data,usecols,kwargs,expected", [
|
| 471 |
+
# see gh-8985
|
| 472 |
+
("19,29,39\n" * 2 + "10,20,30,40", [0, 1, 2],
|
| 473 |
+
dict(header=None), DataFrame([[19, 29, 39], [19, 29, 39], [10, 20, 30]])),
|
| 474 |
+
|
| 475 |
+
# see gh-9549
|
| 476 |
+
(("A,B,C\n1,2,3\n3,4,5\n1,2,4,5,1,6\n"
|
| 477 |
+
"1,2,3,,,1,\n1,2,3\n5,6,7"), ["A", "B", "C"],
|
| 478 |
+
dict(), DataFrame({"A": [1, 3, 1, 1, 1, 5],
|
| 479 |
+
"B": [2, 4, 2, 2, 2, 6],
|
| 480 |
+
"C": [3, 5, 4, 3, 3, 7]})),
|
| 481 |
+
])
|
| 482 |
+
def test_uneven_length_cols(all_parsers, data, usecols, kwargs, expected):
|
| 483 |
+
# see gh-8985
|
| 484 |
+
parser = all_parsers
|
| 485 |
+
result = parser.read_csv(StringIO(data), usecols=usecols, **kwargs)
|
| 486 |
+
tm.assert_frame_equal(result, expected)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
@pytest.mark.parametrize("usecols,kwargs,expected,msg", [
|
| 490 |
+
(["a", "b", "c", "d"], dict(),
|
| 491 |
+
DataFrame({"a": [1, 5], "b": [2, 6], "c": [3, 7], "d": [4, 8]}), None),
|
| 492 |
+
(["a", "b", "c", "f"], dict(), None,
|
| 493 |
+
_msg_validate_usecols_names.format(r"\['f'\]")),
|
| 494 |
+
(["a", "b", "f"], dict(), None,
|
| 495 |
+
_msg_validate_usecols_names.format(r"\['f'\]")),
|
| 496 |
+
(["a", "b", "f", "g"], dict(), None,
|
| 497 |
+
_msg_validate_usecols_names.format(r"\[('f', 'g'|'g', 'f')\]")),
|
| 498 |
+
|
| 499 |
+
# see gh-14671
|
| 500 |
+
(None, dict(header=0, names=["A", "B", "C", "D"]),
|
| 501 |
+
DataFrame({"A": [1, 5], "B": [2, 6], "C": [3, 7],
|
| 502 |
+
"D": [4, 8]}), None),
|
| 503 |
+
(["A", "B", "C", "f"], dict(header=0, names=["A", "B", "C", "D"]),
|
| 504 |
+
None, _msg_validate_usecols_names.format(r"\['f'\]")),
|
| 505 |
+
(["A", "B", "f"], dict(names=["A", "B", "C", "D"]),
|
| 506 |
+
None, _msg_validate_usecols_names.format(r"\['f'\]")),
|
| 507 |
+
])
|
| 508 |
+
def test_raises_on_usecols_names_mismatch(all_parsers, usecols,
|
| 509 |
+
kwargs, expected, msg):
|
| 510 |
+
data = "a,b,c,d\n1,2,3,4\n5,6,7,8"
|
| 511 |
+
kwargs.update(usecols=usecols)
|
| 512 |
+
parser = all_parsers
|
| 513 |
+
|
| 514 |
+
if expected is None:
|
| 515 |
+
with pytest.raises(ValueError, match=msg):
|
| 516 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 517 |
+
else:
|
| 518 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 519 |
+
tm.assert_frame_equal(result, expected)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
@pytest.mark.xfail(
|
| 523 |
+
reason="see gh-16469: works on the C engine but not the Python engine",
|
| 524 |
+
strict=False)
|
| 525 |
+
@pytest.mark.parametrize("usecols", [["A", "C"], [0, 2]])
|
| 526 |
+
def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols):
|
| 527 |
+
data = "a,b,c,d\n1,2,3,4\n5,6,7,8"
|
| 528 |
+
names = ["A", "B", "C", "D"]
|
| 529 |
+
parser = all_parsers
|
| 530 |
+
|
| 531 |
+
result = parser.read_csv(StringIO(data), header=0,
|
| 532 |
+
names=names, usecols=usecols)
|
| 533 |
+
expected = DataFrame({"A": [1, 5], "C": [3, 7]})
|
| 534 |
+
tm.assert_frame_equal(result, expected)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_duplicates.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas import Categorical, Series
|
| 7 |
+
import pandas.util.testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_value_counts_nunique():
|
| 11 |
+
# basics.rst doc example
|
| 12 |
+
series = Series(np.random.randn(500))
|
| 13 |
+
series[20:500] = np.nan
|
| 14 |
+
series[10:20] = 5000
|
| 15 |
+
result = series.nunique()
|
| 16 |
+
assert result == 11
|
| 17 |
+
|
| 18 |
+
# GH 18051
|
| 19 |
+
s = Series(Categorical([]))
|
| 20 |
+
assert s.nunique() == 0
|
| 21 |
+
s = Series(Categorical([np.nan]))
|
| 22 |
+
assert s.nunique() == 0
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_unique():
|
| 26 |
+
# GH714 also, dtype=float
|
| 27 |
+
s = Series([1.2345] * 100)
|
| 28 |
+
s[::2] = np.nan
|
| 29 |
+
result = s.unique()
|
| 30 |
+
assert len(result) == 2
|
| 31 |
+
|
| 32 |
+
s = Series([1.2345] * 100, dtype='f4')
|
| 33 |
+
s[::2] = np.nan
|
| 34 |
+
result = s.unique()
|
| 35 |
+
assert len(result) == 2
|
| 36 |
+
|
| 37 |
+
# NAs in object arrays #714
|
| 38 |
+
s = Series(['foo'] * 100, dtype='O')
|
| 39 |
+
s[::2] = np.nan
|
| 40 |
+
result = s.unique()
|
| 41 |
+
assert len(result) == 2
|
| 42 |
+
|
| 43 |
+
# decision about None
|
| 44 |
+
s = Series([1, 2, 3, None, None, None], dtype=object)
|
| 45 |
+
result = s.unique()
|
| 46 |
+
expected = np.array([1, 2, 3, None], dtype=object)
|
| 47 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 48 |
+
|
| 49 |
+
# GH 18051
|
| 50 |
+
s = Series(Categorical([]))
|
| 51 |
+
tm.assert_categorical_equal(s.unique(), Categorical([]), check_dtype=False)
|
| 52 |
+
s = Series(Categorical([np.nan]))
|
| 53 |
+
tm.assert_categorical_equal(s.unique(), Categorical([np.nan]),
|
| 54 |
+
check_dtype=False)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_unique_data_ownership():
|
| 58 |
+
# it works! #1807
|
| 59 |
+
Series(Series(["a", "c", "b"]).unique()).sort_values()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@pytest.mark.parametrize('data, expected', [
|
| 63 |
+
(np.random.randint(0, 10, size=1000), False),
|
| 64 |
+
(np.arange(1000), True),
|
| 65 |
+
([], True),
|
| 66 |
+
([np.nan], True),
|
| 67 |
+
(['foo', 'bar', np.nan], True),
|
| 68 |
+
(['foo', 'foo', np.nan], False),
|
| 69 |
+
(['foo', 'bar', np.nan, np.nan], False)])
|
| 70 |
+
def test_is_unique(data, expected):
|
| 71 |
+
# GH11946 / GH25180
|
| 72 |
+
s = Series(data)
|
| 73 |
+
assert s.is_unique is expected
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_is_unique_class_ne(capsys):
|
| 77 |
+
# GH 20661
|
| 78 |
+
class Foo(object):
|
| 79 |
+
def __init__(self, val):
|
| 80 |
+
self._value = val
|
| 81 |
+
|
| 82 |
+
def __ne__(self, other):
|
| 83 |
+
raise Exception("NEQ not supported")
|
| 84 |
+
|
| 85 |
+
with capsys.disabled():
|
| 86 |
+
li = [Foo(i) for i in range(5)]
|
| 87 |
+
s = Series(li, index=[i for i in range(5)])
|
| 88 |
+
s.is_unique
|
| 89 |
+
captured = capsys.readouterr()
|
| 90 |
+
assert len(captured.err) == 0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@pytest.mark.parametrize(
|
| 94 |
+
'keep, expected',
|
| 95 |
+
[
|
| 96 |
+
('first', Series([False, False, False, False, True, True, False])),
|
| 97 |
+
('last', Series([False, True, True, False, False, False, False])),
|
| 98 |
+
(False, Series([False, True, True, False, True, True, False]))
|
| 99 |
+
])
|
| 100 |
+
def test_drop_duplicates(any_numpy_dtype, keep, expected):
|
| 101 |
+
tc = Series([1, 0, 3, 5, 3, 0, 4], dtype=np.dtype(any_numpy_dtype))
|
| 102 |
+
|
| 103 |
+
if tc.dtype == 'bool':
|
| 104 |
+
pytest.skip('tested separately in test_drop_duplicates_bool')
|
| 105 |
+
|
| 106 |
+
tm.assert_series_equal(tc.duplicated(keep=keep), expected)
|
| 107 |
+
tm.assert_series_equal(tc.drop_duplicates(keep=keep), tc[~expected])
|
| 108 |
+
sc = tc.copy()
|
| 109 |
+
sc.drop_duplicates(keep=keep, inplace=True)
|
| 110 |
+
tm.assert_series_equal(sc, tc[~expected])
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@pytest.mark.parametrize('keep, expected',
|
| 114 |
+
[('first', Series([False, False, True, True])),
|
| 115 |
+
('last', Series([True, True, False, False])),
|
| 116 |
+
(False, Series([True, True, True, True]))])
|
| 117 |
+
def test_drop_duplicates_bool(keep, expected):
|
| 118 |
+
tc = Series([True, False, True, False])
|
| 119 |
+
|
| 120 |
+
tm.assert_series_equal(tc.duplicated(keep=keep), expected)
|
| 121 |
+
tm.assert_series_equal(tc.drop_duplicates(keep=keep), tc[~expected])
|
| 122 |
+
sc = tc.copy()
|
| 123 |
+
sc.drop_duplicates(keep=keep, inplace=True)
|
| 124 |
+
tm.assert_series_equal(sc, tc[~expected])
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@pytest.mark.parametrize('keep, expected', [
|
| 128 |
+
('first', Series([False, False, True, False, True], name='name')),
|
| 129 |
+
('last', Series([True, True, False, False, False], name='name')),
|
| 130 |
+
(False, Series([True, True, True, False, True], name='name'))
|
| 131 |
+
])
|
| 132 |
+
def test_duplicated_keep(keep, expected):
|
| 133 |
+
s = Series(['a', 'b', 'b', 'c', 'a'], name='name')
|
| 134 |
+
|
| 135 |
+
result = s.duplicated(keep=keep)
|
| 136 |
+
tm.assert_series_equal(result, expected)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@pytest.mark.parametrize('keep, expected', [
|
| 140 |
+
('first', Series([False, False, True, False, True])),
|
| 141 |
+
('last', Series([True, True, False, False, False])),
|
| 142 |
+
(False, Series([True, True, True, False, True]))
|
| 143 |
+
])
|
| 144 |
+
def test_duplicated_nan_none(keep, expected):
|
| 145 |
+
s = Series([np.nan, 3, 3, None, np.nan], dtype=object)
|
| 146 |
+
|
| 147 |
+
result = s.duplicated(keep=keep)
|
| 148 |
+
tm.assert_series_equal(result, expected)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_internals.py
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# pylint: disable-msg=E1101,W0612
|
| 3 |
+
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from pandas import NaT, Series, Timestamp
|
| 11 |
+
from pandas.core.internals.blocks import IntBlock
|
| 12 |
+
import pandas.util.testing as tm
|
| 13 |
+
from pandas.util.testing import assert_series_equal
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestSeriesInternals(object):
|
| 17 |
+
|
| 18 |
+
def test_convert_objects(self):
|
| 19 |
+
|
| 20 |
+
s = Series([1., 2, 3], index=['a', 'b', 'c'])
|
| 21 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 22 |
+
result = s.convert_objects(convert_dates=False,
|
| 23 |
+
convert_numeric=True)
|
| 24 |
+
assert_series_equal(result, s)
|
| 25 |
+
|
| 26 |
+
# force numeric conversion
|
| 27 |
+
r = s.copy().astype('O')
|
| 28 |
+
r['a'] = '1'
|
| 29 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 30 |
+
result = r.convert_objects(convert_dates=False,
|
| 31 |
+
convert_numeric=True)
|
| 32 |
+
assert_series_equal(result, s)
|
| 33 |
+
|
| 34 |
+
r = s.copy().astype('O')
|
| 35 |
+
r['a'] = '1.'
|
| 36 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 37 |
+
result = r.convert_objects(convert_dates=False,
|
| 38 |
+
convert_numeric=True)
|
| 39 |
+
assert_series_equal(result, s)
|
| 40 |
+
|
| 41 |
+
r = s.copy().astype('O')
|
| 42 |
+
r['a'] = 'garbled'
|
| 43 |
+
expected = s.copy()
|
| 44 |
+
expected['a'] = np.nan
|
| 45 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 46 |
+
result = r.convert_objects(convert_dates=False,
|
| 47 |
+
convert_numeric=True)
|
| 48 |
+
assert_series_equal(result, expected)
|
| 49 |
+
|
| 50 |
+
# GH 4119, not converting a mixed type (e.g.floats and object)
|
| 51 |
+
s = Series([1, 'na', 3, 4])
|
| 52 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 53 |
+
result = s.convert_objects(convert_numeric=True)
|
| 54 |
+
expected = Series([1, np.nan, 3, 4])
|
| 55 |
+
assert_series_equal(result, expected)
|
| 56 |
+
|
| 57 |
+
s = Series([1, '', 3, 4])
|
| 58 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 59 |
+
result = s.convert_objects(convert_numeric=True)
|
| 60 |
+
expected = Series([1, np.nan, 3, 4])
|
| 61 |
+
assert_series_equal(result, expected)
|
| 62 |
+
|
| 63 |
+
# dates
|
| 64 |
+
s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
|
| 65 |
+
datetime(2001, 1, 3, 0, 0)])
|
| 66 |
+
s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
|
| 67 |
+
datetime(2001, 1, 3, 0, 0), 'foo', 1.0, 1,
|
| 68 |
+
Timestamp('20010104'), '20010105'],
|
| 69 |
+
dtype='O')
|
| 70 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 71 |
+
result = s.convert_objects(convert_dates=True,
|
| 72 |
+
convert_numeric=False)
|
| 73 |
+
expected = Series([Timestamp('20010101'), Timestamp('20010102'),
|
| 74 |
+
Timestamp('20010103')], dtype='M8[ns]')
|
| 75 |
+
assert_series_equal(result, expected)
|
| 76 |
+
|
| 77 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 78 |
+
result = s.convert_objects(convert_dates='coerce',
|
| 79 |
+
convert_numeric=False)
|
| 80 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 81 |
+
result = s.convert_objects(convert_dates='coerce',
|
| 82 |
+
convert_numeric=True)
|
| 83 |
+
assert_series_equal(result, expected)
|
| 84 |
+
|
| 85 |
+
expected = Series([Timestamp('20010101'), Timestamp('20010102'),
|
| 86 |
+
Timestamp('20010103'),
|
| 87 |
+
NaT, NaT, NaT, Timestamp('20010104'),
|
| 88 |
+
Timestamp('20010105')], dtype='M8[ns]')
|
| 89 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 90 |
+
result = s2.convert_objects(convert_dates='coerce',
|
| 91 |
+
convert_numeric=False)
|
| 92 |
+
assert_series_equal(result, expected)
|
| 93 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 94 |
+
result = s2.convert_objects(convert_dates='coerce',
|
| 95 |
+
convert_numeric=True)
|
| 96 |
+
assert_series_equal(result, expected)
|
| 97 |
+
|
| 98 |
+
# preserver all-nans (if convert_dates='coerce')
|
| 99 |
+
s = Series(['foo', 'bar', 1, 1.0], dtype='O')
|
| 100 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 101 |
+
result = s.convert_objects(convert_dates='coerce',
|
| 102 |
+
convert_numeric=False)
|
| 103 |
+
expected = Series([NaT] * 2 + [Timestamp(1)] * 2)
|
| 104 |
+
assert_series_equal(result, expected)
|
| 105 |
+
|
| 106 |
+
# preserver if non-object
|
| 107 |
+
s = Series([1], dtype='float32')
|
| 108 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 109 |
+
result = s.convert_objects(convert_dates='coerce',
|
| 110 |
+
convert_numeric=False)
|
| 111 |
+
assert_series_equal(result, s)
|
| 112 |
+
|
| 113 |
+
# r = s.copy()
|
| 114 |
+
# r[0] = np.nan
|
| 115 |
+
# result = r.convert_objects(convert_dates=True,convert_numeric=False)
|
| 116 |
+
# assert result.dtype == 'M8[ns]'
|
| 117 |
+
|
| 118 |
+
# dateutil parses some single letters into today's value as a date
|
| 119 |
+
for x in 'abcdefghijklmnopqrstuvwxyz':
|
| 120 |
+
s = Series([x])
|
| 121 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 122 |
+
result = s.convert_objects(convert_dates='coerce')
|
| 123 |
+
assert_series_equal(result, s)
|
| 124 |
+
s = Series([x.upper()])
|
| 125 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 126 |
+
result = s.convert_objects(convert_dates='coerce')
|
| 127 |
+
assert_series_equal(result, s)
|
| 128 |
+
|
| 129 |
+
def test_convert_objects_preserve_bool(self):
|
| 130 |
+
s = Series([1, True, 3, 5], dtype=object)
|
| 131 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 132 |
+
r = s.convert_objects(convert_numeric=True)
|
| 133 |
+
e = Series([1, 1, 3, 5], dtype='i8')
|
| 134 |
+
tm.assert_series_equal(r, e)
|
| 135 |
+
|
| 136 |
+
def test_convert_objects_preserve_all_bool(self):
|
| 137 |
+
s = Series([False, True, False, False], dtype=object)
|
| 138 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 139 |
+
r = s.convert_objects(convert_numeric=True)
|
| 140 |
+
e = Series([False, True, False, False], dtype=bool)
|
| 141 |
+
tm.assert_series_equal(r, e)
|
| 142 |
+
|
| 143 |
+
# GH 10265
|
| 144 |
+
def test_convert(self):
|
| 145 |
+
# Tests: All to nans, coerce, true
|
| 146 |
+
# Test coercion returns correct type
|
| 147 |
+
s = Series(['a', 'b', 'c'])
|
| 148 |
+
results = s._convert(datetime=True, coerce=True)
|
| 149 |
+
expected = Series([NaT] * 3)
|
| 150 |
+
assert_series_equal(results, expected)
|
| 151 |
+
|
| 152 |
+
results = s._convert(numeric=True, coerce=True)
|
| 153 |
+
expected = Series([np.nan] * 3)
|
| 154 |
+
assert_series_equal(results, expected)
|
| 155 |
+
|
| 156 |
+
expected = Series([NaT] * 3, dtype=np.dtype('m8[ns]'))
|
| 157 |
+
results = s._convert(timedelta=True, coerce=True)
|
| 158 |
+
assert_series_equal(results, expected)
|
| 159 |
+
|
| 160 |
+
dt = datetime(2001, 1, 1, 0, 0)
|
| 161 |
+
td = dt - datetime(2000, 1, 1, 0, 0)
|
| 162 |
+
|
| 163 |
+
# Test coercion with mixed types
|
| 164 |
+
s = Series(['a', '3.1415', dt, td])
|
| 165 |
+
results = s._convert(datetime=True, coerce=True)
|
| 166 |
+
expected = Series([NaT, NaT, dt, NaT])
|
| 167 |
+
assert_series_equal(results, expected)
|
| 168 |
+
|
| 169 |
+
results = s._convert(numeric=True, coerce=True)
|
| 170 |
+
expected = Series([np.nan, 3.1415, np.nan, np.nan])
|
| 171 |
+
assert_series_equal(results, expected)
|
| 172 |
+
|
| 173 |
+
results = s._convert(timedelta=True, coerce=True)
|
| 174 |
+
expected = Series([NaT, NaT, NaT, td],
|
| 175 |
+
dtype=np.dtype('m8[ns]'))
|
| 176 |
+
assert_series_equal(results, expected)
|
| 177 |
+
|
| 178 |
+
# Test standard conversion returns original
|
| 179 |
+
results = s._convert(datetime=True)
|
| 180 |
+
assert_series_equal(results, s)
|
| 181 |
+
results = s._convert(numeric=True)
|
| 182 |
+
expected = Series([np.nan, 3.1415, np.nan, np.nan])
|
| 183 |
+
assert_series_equal(results, expected)
|
| 184 |
+
results = s._convert(timedelta=True)
|
| 185 |
+
assert_series_equal(results, s)
|
| 186 |
+
|
| 187 |
+
# test pass-through and non-conversion when other types selected
|
| 188 |
+
s = Series(['1.0', '2.0', '3.0'])
|
| 189 |
+
results = s._convert(datetime=True, numeric=True, timedelta=True)
|
| 190 |
+
expected = Series([1.0, 2.0, 3.0])
|
| 191 |
+
assert_series_equal(results, expected)
|
| 192 |
+
results = s._convert(True, False, True)
|
| 193 |
+
assert_series_equal(results, s)
|
| 194 |
+
|
| 195 |
+
s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)],
|
| 196 |
+
dtype='O')
|
| 197 |
+
results = s._convert(datetime=True, numeric=True, timedelta=True)
|
| 198 |
+
expected = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0,
|
| 199 |
+
0)])
|
| 200 |
+
assert_series_equal(results, expected)
|
| 201 |
+
results = s._convert(datetime=False, numeric=True, timedelta=True)
|
| 202 |
+
assert_series_equal(results, s)
|
| 203 |
+
|
| 204 |
+
td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0)
|
| 205 |
+
s = Series([td, td], dtype='O')
|
| 206 |
+
results = s._convert(datetime=True, numeric=True, timedelta=True)
|
| 207 |
+
expected = Series([td, td])
|
| 208 |
+
assert_series_equal(results, expected)
|
| 209 |
+
results = s._convert(True, True, False)
|
| 210 |
+
assert_series_equal(results, s)
|
| 211 |
+
|
| 212 |
+
s = Series([1., 2, 3], index=['a', 'b', 'c'])
|
| 213 |
+
result = s._convert(numeric=True)
|
| 214 |
+
assert_series_equal(result, s)
|
| 215 |
+
|
| 216 |
+
# force numeric conversion
|
| 217 |
+
r = s.copy().astype('O')
|
| 218 |
+
r['a'] = '1'
|
| 219 |
+
result = r._convert(numeric=True)
|
| 220 |
+
assert_series_equal(result, s)
|
| 221 |
+
|
| 222 |
+
r = s.copy().astype('O')
|
| 223 |
+
r['a'] = '1.'
|
| 224 |
+
result = r._convert(numeric=True)
|
| 225 |
+
assert_series_equal(result, s)
|
| 226 |
+
|
| 227 |
+
r = s.copy().astype('O')
|
| 228 |
+
r['a'] = 'garbled'
|
| 229 |
+
result = r._convert(numeric=True)
|
| 230 |
+
expected = s.copy()
|
| 231 |
+
expected['a'] = np.nan
|
| 232 |
+
assert_series_equal(result, expected)
|
| 233 |
+
|
| 234 |
+
# GH 4119, not converting a mixed type (e.g.floats and object)
|
| 235 |
+
s = Series([1, 'na', 3, 4])
|
| 236 |
+
result = s._convert(datetime=True, numeric=True)
|
| 237 |
+
expected = Series([1, np.nan, 3, 4])
|
| 238 |
+
assert_series_equal(result, expected)
|
| 239 |
+
|
| 240 |
+
s = Series([1, '', 3, 4])
|
| 241 |
+
result = s._convert(datetime=True, numeric=True)
|
| 242 |
+
assert_series_equal(result, expected)
|
| 243 |
+
|
| 244 |
+
# dates
|
| 245 |
+
s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
|
| 246 |
+
datetime(2001, 1, 3, 0, 0)])
|
| 247 |
+
s2 = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 2, 0, 0),
|
| 248 |
+
datetime(2001, 1, 3, 0, 0), 'foo', 1.0, 1,
|
| 249 |
+
Timestamp('20010104'), '20010105'], dtype='O')
|
| 250 |
+
|
| 251 |
+
result = s._convert(datetime=True)
|
| 252 |
+
expected = Series([Timestamp('20010101'), Timestamp('20010102'),
|
| 253 |
+
Timestamp('20010103')], dtype='M8[ns]')
|
| 254 |
+
assert_series_equal(result, expected)
|
| 255 |
+
|
| 256 |
+
result = s._convert(datetime=True, coerce=True)
|
| 257 |
+
assert_series_equal(result, expected)
|
| 258 |
+
|
| 259 |
+
expected = Series([Timestamp('20010101'), Timestamp('20010102'),
|
| 260 |
+
Timestamp('20010103'), NaT, NaT, NaT,
|
| 261 |
+
Timestamp('20010104'), Timestamp('20010105')],
|
| 262 |
+
dtype='M8[ns]')
|
| 263 |
+
result = s2._convert(datetime=True, numeric=False, timedelta=False,
|
| 264 |
+
coerce=True)
|
| 265 |
+
assert_series_equal(result, expected)
|
| 266 |
+
result = s2._convert(datetime=True, coerce=True)
|
| 267 |
+
assert_series_equal(result, expected)
|
| 268 |
+
|
| 269 |
+
s = Series(['foo', 'bar', 1, 1.0], dtype='O')
|
| 270 |
+
result = s._convert(datetime=True, coerce=True)
|
| 271 |
+
expected = Series([NaT] * 2 + [Timestamp(1)] * 2)
|
| 272 |
+
assert_series_equal(result, expected)
|
| 273 |
+
|
| 274 |
+
# preserver if non-object
|
| 275 |
+
s = Series([1], dtype='float32')
|
| 276 |
+
result = s._convert(datetime=True, coerce=True)
|
| 277 |
+
assert_series_equal(result, s)
|
| 278 |
+
|
| 279 |
+
# r = s.copy()
|
| 280 |
+
# r[0] = np.nan
|
| 281 |
+
# result = r._convert(convert_dates=True,convert_numeric=False)
|
| 282 |
+
# assert result.dtype == 'M8[ns]'
|
| 283 |
+
|
| 284 |
+
# dateutil parses some single letters into today's value as a date
|
| 285 |
+
expected = Series([NaT])
|
| 286 |
+
for x in 'abcdefghijklmnopqrstuvwxyz':
|
| 287 |
+
s = Series([x])
|
| 288 |
+
result = s._convert(datetime=True, coerce=True)
|
| 289 |
+
assert_series_equal(result, expected)
|
| 290 |
+
s = Series([x.upper()])
|
| 291 |
+
result = s._convert(datetime=True, coerce=True)
|
| 292 |
+
assert_series_equal(result, expected)
|
| 293 |
+
|
| 294 |
+
def test_convert_no_arg_error(self):
|
| 295 |
+
s = Series(['1.0', '2'])
|
| 296 |
+
msg = r"At least one of datetime, numeric or timedelta must be True\."
|
| 297 |
+
with pytest.raises(ValueError, match=msg):
|
| 298 |
+
s._convert()
|
| 299 |
+
|
| 300 |
+
def test_convert_preserve_bool(self):
|
| 301 |
+
s = Series([1, True, 3, 5], dtype=object)
|
| 302 |
+
r = s._convert(datetime=True, numeric=True)
|
| 303 |
+
e = Series([1, 1, 3, 5], dtype='i8')
|
| 304 |
+
tm.assert_series_equal(r, e)
|
| 305 |
+
|
| 306 |
+
def test_convert_preserve_all_bool(self):
|
| 307 |
+
s = Series([False, True, False, False], dtype=object)
|
| 308 |
+
r = s._convert(datetime=True, numeric=True)
|
| 309 |
+
e = Series([False, True, False, False], dtype=bool)
|
| 310 |
+
tm.assert_series_equal(r, e)
|
| 311 |
+
|
| 312 |
+
def test_constructor_no_pandas_array(self):
|
| 313 |
+
ser = pd.Series([1, 2, 3])
|
| 314 |
+
result = pd.Series(ser.array)
|
| 315 |
+
tm.assert_series_equal(ser, result)
|
| 316 |
+
assert isinstance(result._data.blocks[0], IntBlock)
|
| 317 |
+
|
| 318 |
+
def test_from_array(self):
|
| 319 |
+
result = pd.Series(pd.array(['1H', '2H'], dtype='timedelta64[ns]'))
|
| 320 |
+
assert result._data.blocks[0].is_extension is False
|
| 321 |
+
|
| 322 |
+
result = pd.Series(pd.array(['2015'], dtype='datetime64[ns]'))
|
| 323 |
+
assert result._data.blocks[0].is_extension is False
|
| 324 |
+
|
| 325 |
+
def test_from_list_dtype(self):
|
| 326 |
+
result = pd.Series(['1H', '2H'], dtype='timedelta64[ns]')
|
| 327 |
+
assert result._data.blocks[0].is_extension is False
|
| 328 |
+
|
| 329 |
+
result = pd.Series(['2015'], dtype='datetime64[ns]')
|
| 330 |
+
assert result._data.blocks[0].is_extension is False
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def test_hasnans_unchached_for_series():
|
| 334 |
+
# GH#19700
|
| 335 |
+
idx = pd.Index([0, 1])
|
| 336 |
+
assert idx.hasnans is False
|
| 337 |
+
assert 'hasnans' in idx._cache
|
| 338 |
+
ser = idx.to_series()
|
| 339 |
+
assert ser.hasnans is False
|
| 340 |
+
assert not hasattr(ser, '_cache')
|
| 341 |
+
ser.iloc[-1] = np.nan
|
| 342 |
+
assert ser.hasnans is True
|
| 343 |
+
assert Series.hasnans.__doc__ == pd.Index.hasnans.__doc__
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/series/test_io.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# pylint: disable-msg=E1101,W0612
|
| 3 |
+
|
| 4 |
+
import collections
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from pandas.compat import StringIO, u
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from pandas import DataFrame, Series
|
| 14 |
+
import pandas.util.testing as tm
|
| 15 |
+
from pandas.util.testing import (
|
| 16 |
+
assert_almost_equal, assert_frame_equal, assert_series_equal, ensure_clean)
|
| 17 |
+
|
| 18 |
+
from pandas.io.common import _get_handle
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestSeriesToCSV():
|
| 22 |
+
|
| 23 |
+
def read_csv(self, path, **kwargs):
|
| 24 |
+
params = dict(squeeze=True, index_col=0,
|
| 25 |
+
header=None, parse_dates=True)
|
| 26 |
+
params.update(**kwargs)
|
| 27 |
+
|
| 28 |
+
header = params.get("header")
|
| 29 |
+
out = pd.read_csv(path, **params)
|
| 30 |
+
|
| 31 |
+
if header is None:
|
| 32 |
+
out.name = out.index.name = None
|
| 33 |
+
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
def test_from_csv_deprecation(self, datetime_series):
|
| 37 |
+
# see gh-17812
|
| 38 |
+
with ensure_clean() as path:
|
| 39 |
+
datetime_series.to_csv(path, header=False)
|
| 40 |
+
|
| 41 |
+
with tm.assert_produces_warning(FutureWarning,
|
| 42 |
+
check_stacklevel=False):
|
| 43 |
+
ts = self.read_csv(path)
|
| 44 |
+
depr_ts = Series.from_csv(path)
|
| 45 |
+
assert_series_equal(depr_ts, ts)
|
| 46 |
+
|
| 47 |
+
@pytest.mark.parametrize("arg", ["path", "header", "both"])
|
| 48 |
+
def test_to_csv_deprecation(self, arg, datetime_series):
|
| 49 |
+
# see gh-19715
|
| 50 |
+
with ensure_clean() as path:
|
| 51 |
+
if arg == "path":
|
| 52 |
+
kwargs = dict(path=path, header=False)
|
| 53 |
+
elif arg == "header":
|
| 54 |
+
kwargs = dict(path_or_buf=path)
|
| 55 |
+
else: # Both discrepancies match.
|
| 56 |
+
kwargs = dict(path=path)
|
| 57 |
+
|
| 58 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 59 |
+
datetime_series.to_csv(**kwargs)
|
| 60 |
+
|
| 61 |
+
# Make sure roundtrip still works.
|
| 62 |
+
ts = self.read_csv(path)
|
| 63 |
+
assert_series_equal(datetime_series, ts, check_names=False)
|
| 64 |
+
|
| 65 |
+
def test_from_csv(self, datetime_series, string_series):
|
| 66 |
+
|
| 67 |
+
with ensure_clean() as path:
|
| 68 |
+
datetime_series.to_csv(path, header=False)
|
| 69 |
+
ts = self.read_csv(path)
|
| 70 |
+
assert_series_equal(datetime_series, ts, check_names=False)
|
| 71 |
+
|
| 72 |
+
assert ts.name is None
|
| 73 |
+
assert ts.index.name is None
|
| 74 |
+
|
| 75 |
+
with tm.assert_produces_warning(FutureWarning,
|
| 76 |
+
check_stacklevel=False):
|
| 77 |
+
depr_ts = Series.from_csv(path)
|
| 78 |
+
assert_series_equal(depr_ts, ts)
|
| 79 |
+
|
| 80 |
+
# see gh-10483
|
| 81 |
+
datetime_series.to_csv(path, header=True)
|
| 82 |
+
ts_h = self.read_csv(path, header=0)
|
| 83 |
+
assert ts_h.name == "ts"
|
| 84 |
+
|
| 85 |
+
string_series.to_csv(path, header=False)
|
| 86 |
+
series = self.read_csv(path)
|
| 87 |
+
assert_series_equal(string_series, series, check_names=False)
|
| 88 |
+
|
| 89 |
+
assert series.name is None
|
| 90 |
+
assert series.index.name is None
|
| 91 |
+
|
| 92 |
+
string_series.to_csv(path, header=True)
|
| 93 |
+
series_h = self.read_csv(path, header=0)
|
| 94 |
+
assert series_h.name == "series"
|
| 95 |
+
|
| 96 |
+
with open(path, "w") as outfile:
|
| 97 |
+
outfile.write("1998-01-01|1.0\n1999-01-01|2.0")
|
| 98 |
+
|
| 99 |
+
series = self.read_csv(path, sep="|")
|
| 100 |
+
check_series = Series({datetime(1998, 1, 1): 1.0,
|
| 101 |
+
datetime(1999, 1, 1): 2.0})
|
| 102 |
+
assert_series_equal(check_series, series)
|
| 103 |
+
|
| 104 |
+
series = self.read_csv(path, sep="|", parse_dates=False)
|
| 105 |
+
check_series = Series({"1998-01-01": 1.0, "1999-01-01": 2.0})
|
| 106 |
+
assert_series_equal(check_series, series)
|
| 107 |
+
|
| 108 |
+
def test_to_csv(self, datetime_series):
|
| 109 |
+
import io
|
| 110 |
+
|
| 111 |
+
with ensure_clean() as path:
|
| 112 |
+
datetime_series.to_csv(path, header=False)
|
| 113 |
+
|
| 114 |
+
with io.open(path, newline=None) as f:
|
| 115 |
+
lines = f.readlines()
|
| 116 |
+
assert (lines[1] != '\n')
|
| 117 |
+
|
| 118 |
+
datetime_series.to_csv(path, index=False, header=False)
|
| 119 |
+
arr = np.loadtxt(path)
|
| 120 |
+
assert_almost_equal(arr, datetime_series.values)
|
| 121 |
+
|
| 122 |
+
def test_to_csv_unicode_index(self):
|
| 123 |
+
buf = StringIO()
|
| 124 |
+
s = Series([u("\u05d0"), "d2"], index=[u("\u05d0"), u("\u05d1")])
|
| 125 |
+
|
| 126 |
+
s.to_csv(buf, encoding="UTF-8", header=False)
|
| 127 |
+
buf.seek(0)
|
| 128 |
+
|
| 129 |
+
s2 = self.read_csv(buf, index_col=0, encoding="UTF-8")
|
| 130 |
+
assert_series_equal(s, s2)
|
| 131 |
+
|
| 132 |
+
def test_to_csv_float_format(self):
|
| 133 |
+
|
| 134 |
+
with ensure_clean() as filename:
|
| 135 |
+
ser = Series([0.123456, 0.234567, 0.567567])
|
| 136 |
+
ser.to_csv(filename, float_format="%.2f", header=False)
|
| 137 |
+
|
| 138 |
+
rs = self.read_csv(filename)
|
| 139 |
+
xp = Series([0.12, 0.23, 0.57])
|
| 140 |
+
assert_series_equal(rs, xp)
|
| 141 |
+
|
| 142 |
+
def test_to_csv_list_entries(self):
|
| 143 |
+
s = Series(['jack and jill', 'jesse and frank'])
|
| 144 |
+
|
| 145 |
+
split = s.str.split(r'\s+and\s+')
|
| 146 |
+
|
| 147 |
+
buf = StringIO()
|
| 148 |
+
split.to_csv(buf, header=False)
|
| 149 |
+
|
| 150 |
+
def test_to_csv_path_is_none(self):
|
| 151 |
+
# GH 8215
|
| 152 |
+
# Series.to_csv() was returning None, inconsistent with
|
| 153 |
+
# DataFrame.to_csv() which returned string
|
| 154 |
+
s = Series([1, 2, 3])
|
| 155 |
+
csv_str = s.to_csv(path_or_buf=None, header=False)
|
| 156 |
+
assert isinstance(csv_str, str)
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize('s,encoding', [
|
| 159 |
+
(Series([0.123456, 0.234567, 0.567567], index=['A', 'B', 'C'],
|
| 160 |
+
name='X'), None),
|
| 161 |
+
# GH 21241, 21118
|
| 162 |
+
(Series(['abc', 'def', 'ghi'], name='X'), 'ascii'),
|
| 163 |
+
(Series(["123", u"你好", u"世界"], name=u"中文"), 'gb2312'),
|
| 164 |
+
(Series(["123", u"Γειά σου", u"Κόσμε"], name=u"Ελληνικά"), 'cp737')
|
| 165 |
+
])
|
| 166 |
+
def test_to_csv_compression(self, s, encoding, compression):
|
| 167 |
+
|
| 168 |
+
with ensure_clean() as filename:
|
| 169 |
+
|
| 170 |
+
s.to_csv(filename, compression=compression, encoding=encoding,
|
| 171 |
+
header=True)
|
| 172 |
+
# test the round trip - to_csv -> read_csv
|
| 173 |
+
result = pd.read_csv(filename, compression=compression,
|
| 174 |
+
encoding=encoding, index_col=0, squeeze=True)
|
| 175 |
+
assert_series_equal(s, result)
|
| 176 |
+
|
| 177 |
+
# test the round trip using file handle - to_csv -> read_csv
|
| 178 |
+
f, _handles = _get_handle(filename, 'w', compression=compression,
|
| 179 |
+
encoding=encoding)
|
| 180 |
+
with f:
|
| 181 |
+
s.to_csv(f, encoding=encoding, header=True)
|
| 182 |
+
result = pd.read_csv(filename, compression=compression,
|
| 183 |
+
encoding=encoding, index_col=0, squeeze=True)
|
| 184 |
+
assert_series_equal(s, result)
|
| 185 |
+
|
| 186 |
+
# explicitly ensure file was compressed
|
| 187 |
+
with tm.decompress_file(filename, compression) as fh:
|
| 188 |
+
text = fh.read().decode(encoding or 'utf8')
|
| 189 |
+
assert s.name in text
|
| 190 |
+
|
| 191 |
+
with tm.decompress_file(filename, compression) as fh:
|
| 192 |
+
assert_series_equal(s, pd.read_csv(fh,
|
| 193 |
+
index_col=0,
|
| 194 |
+
squeeze=True,
|
| 195 |
+
encoding=encoding))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class TestSeriesIO():
|
| 199 |
+
|
| 200 |
+
def test_to_frame(self, datetime_series):
|
| 201 |
+
datetime_series.name = None
|
| 202 |
+
rs = datetime_series.to_frame()
|
| 203 |
+
xp = pd.DataFrame(datetime_series.values, index=datetime_series.index)
|
| 204 |
+
assert_frame_equal(rs, xp)
|
| 205 |
+
|
| 206 |
+
datetime_series.name = 'testname'
|
| 207 |
+
rs = datetime_series.to_frame()
|
| 208 |
+
xp = pd.DataFrame(dict(testname=datetime_series.values),
|
| 209 |
+
index=datetime_series.index)
|
| 210 |
+
assert_frame_equal(rs, xp)
|
| 211 |
+
|
| 212 |
+
rs = datetime_series.to_frame(name='testdifferent')
|
| 213 |
+
xp = pd.DataFrame(dict(testdifferent=datetime_series.values),
|
| 214 |
+
index=datetime_series.index)
|
| 215 |
+
assert_frame_equal(rs, xp)
|
| 216 |
+
|
| 217 |
+
def test_timeseries_periodindex(self):
|
| 218 |
+
# GH2891
|
| 219 |
+
from pandas import period_range
|
| 220 |
+
prng = period_range('1/1/2011', '1/1/2012', freq='M')
|
| 221 |
+
ts = Series(np.random.randn(len(prng)), prng)
|
| 222 |
+
new_ts = tm.round_trip_pickle(ts)
|
| 223 |
+
assert new_ts.index.freq == 'M'
|
| 224 |
+
|
| 225 |
+
def test_pickle_preserve_name(self):
|
| 226 |
+
for n in [777, 777., 'name', datetime(2001, 11, 11), (1, 2)]:
|
| 227 |
+
unpickled = self._pickle_roundtrip_name(tm.makeTimeSeries(name=n))
|
| 228 |
+
assert unpickled.name == n
|
| 229 |
+
|
| 230 |
+
def _pickle_roundtrip_name(self, obj):
|
| 231 |
+
|
| 232 |
+
with ensure_clean() as path:
|
| 233 |
+
obj.to_pickle(path)
|
| 234 |
+
unpickled = pd.read_pickle(path)
|
| 235 |
+
return unpickled
|
| 236 |
+
|
| 237 |
+
def test_to_frame_expanddim(self):
|
| 238 |
+
# GH 9762
|
| 239 |
+
|
| 240 |
+
class SubclassedSeries(Series):
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def _constructor_expanddim(self):
|
| 244 |
+
return SubclassedFrame
|
| 245 |
+
|
| 246 |
+
class SubclassedFrame(DataFrame):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
s = SubclassedSeries([1, 2, 3], name='X')
|
| 250 |
+
result = s.to_frame()
|
| 251 |
+
assert isinstance(result, SubclassedFrame)
|
| 252 |
+
expected = SubclassedFrame({'X': [1, 2, 3]})
|
| 253 |
+
assert_frame_equal(result, expected)
|
| 254 |
+
|
| 255 |
+
@pytest.mark.parametrize('mapping', (
|
| 256 |
+
dict,
|
| 257 |
+
collections.defaultdict(list),
|
| 258 |
+
collections.OrderedDict))
|
| 259 |
+
def test_to_dict(self, mapping, datetime_series):
|
| 260 |
+
# GH16122
|
| 261 |
+
tm.assert_series_equal(
|
| 262 |
+
Series(datetime_series.to_dict(mapping), name='ts'),
|
| 263 |
+
datetime_series)
|
| 264 |
+
from_method = Series(datetime_series.to_dict(collections.Counter))
|
| 265 |
+
from_constructor = Series(collections
|
| 266 |
+
.Counter(datetime_series.iteritems()))
|
| 267 |
+
tm.assert_series_equal(from_method, from_constructor)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/__init__.py
ADDED
|
File without changes
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/test_pivot.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pandas.util.testing as tm
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestPivotTable(object):
|
| 8 |
+
|
| 9 |
+
def setup_method(self, method):
|
| 10 |
+
self.dense = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
|
| 11 |
+
'foo', 'bar', 'foo', 'foo'],
|
| 12 |
+
'B': ['one', 'one', 'two', 'three',
|
| 13 |
+
'two', 'two', 'one', 'three'],
|
| 14 |
+
'C': np.random.randn(8),
|
| 15 |
+
'D': np.random.randn(8),
|
| 16 |
+
'E': [np.nan, np.nan, 1, 2,
|
| 17 |
+
np.nan, 1, np.nan, np.nan]})
|
| 18 |
+
self.sparse = self.dense.to_sparse()
|
| 19 |
+
|
| 20 |
+
def test_pivot_table(self):
|
| 21 |
+
res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
|
| 22 |
+
values='C')
|
| 23 |
+
res_dense = pd.pivot_table(self.dense, index='A', columns='B',
|
| 24 |
+
values='C')
|
| 25 |
+
tm.assert_frame_equal(res_sparse, res_dense)
|
| 26 |
+
|
| 27 |
+
res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
|
| 28 |
+
values='E')
|
| 29 |
+
res_dense = pd.pivot_table(self.dense, index='A', columns='B',
|
| 30 |
+
values='E')
|
| 31 |
+
tm.assert_frame_equal(res_sparse, res_dense)
|
| 32 |
+
|
| 33 |
+
res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
|
| 34 |
+
values='E', aggfunc='mean')
|
| 35 |
+
res_dense = pd.pivot_table(self.dense, index='A', columns='B',
|
| 36 |
+
values='E', aggfunc='mean')
|
| 37 |
+
tm.assert_frame_equal(res_sparse, res_dense)
|
| 38 |
+
|
| 39 |
+
# ToDo: sum doesn't handle nan properly
|
| 40 |
+
# res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
|
| 41 |
+
# values='E', aggfunc='sum')
|
| 42 |
+
# res_dense = pd.pivot_table(self.dense, index='A', columns='B',
|
| 43 |
+
# values='E', aggfunc='sum')
|
| 44 |
+
# tm.assert_frame_equal(res_sparse, res_dense)
|
| 45 |
+
|
| 46 |
+
def test_pivot_table_multi(self):
|
| 47 |
+
res_sparse = pd.pivot_table(self.sparse, index='A', columns='B',
|
| 48 |
+
values=['D', 'E'])
|
| 49 |
+
res_dense = pd.pivot_table(self.dense, index='A', columns='B',
|
| 50 |
+
values=['D', 'E'])
|
| 51 |
+
res_dense = res_dense.apply(lambda x: x.astype("Sparse[float64]"))
|
| 52 |
+
tm.assert_frame_equal(res_sparse, res_dense)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/sparse/test_reshape.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pandas.util.testing as tm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def sparse_df():
|
| 10 |
+
return pd.SparseDataFrame({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}) # eye
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture
|
| 14 |
+
def multi_index3():
|
| 15 |
+
return pd.MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)])
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_sparse_frame_stack(sparse_df, multi_index3):
|
| 19 |
+
ss = sparse_df.stack()
|
| 20 |
+
expected = pd.SparseSeries(np.ones(3), index=multi_index3)
|
| 21 |
+
tm.assert_sp_series_equal(ss, expected)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_sparse_frame_unstack(sparse_df):
|
| 25 |
+
mi = pd.MultiIndex.from_tuples([(0, 0), (1, 0), (1, 2)])
|
| 26 |
+
sparse_df.index = mi
|
| 27 |
+
arr = np.array([[1, np.nan, np.nan],
|
| 28 |
+
[np.nan, 1, np.nan],
|
| 29 |
+
[np.nan, np.nan, 1]])
|
| 30 |
+
unstacked_df = pd.DataFrame(arr, index=mi).unstack()
|
| 31 |
+
unstacked_sdf = sparse_df.unstack()
|
| 32 |
+
|
| 33 |
+
tm.assert_numpy_array_equal(unstacked_df.values, unstacked_sdf.values)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_sparse_series_unstack(sparse_df, multi_index3):
|
| 37 |
+
frame = pd.SparseSeries(np.ones(3), index=multi_index3).unstack()
|
| 38 |
+
|
| 39 |
+
arr = np.array([1, np.nan, np.nan])
|
| 40 |
+
arrays = {i: pd.SparseArray(np.roll(arr, i)) for i in range(3)}
|
| 41 |
+
expected = pd.DataFrame(arrays)
|
| 42 |
+
tm.assert_frame_equal(frame, expected)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tools/__init__.py
ADDED
|
File without changes
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tools/test_numeric.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 11 |
+
|
| 12 |
+
class TestToNumeric(object):
|
| 13 |
+
|
| 14 |
+
def test_empty(self):
|
| 15 |
+
# see gh-16302
|
| 16 |
+
s = pd.Series([], dtype=object)
|
| 17 |
+
|
| 18 |
+
res = to_numeric(s)
|
| 19 |
+
expected = pd.Series([], dtype=np.int64)
|
| 20 |
+
|
| 21 |
+
tm.assert_series_equal(res, expected)
|
| 22 |
+
|
| 23 |
+
# Original issue example
|
| 24 |
+
res = to_numeric(s, errors='coerce', downcast='integer')
|
| 25 |
+
expected = pd.Series([], dtype=np.int8)
|
| 26 |
+
|
| 27 |
+
tm.assert_series_equal(res, expected)
|
| 28 |
+
|
| 29 |
+
def test_series(self):
|
| 30 |
+
s = pd.Series(['1', '-3.14', '7'])
|
| 31 |
+
res = to_numeric(s)
|
| 32 |
+
expected = pd.Series([1, -3.14, 7])
|
| 33 |
+
tm.assert_series_equal(res, expected)
|
| 34 |
+
|
| 35 |
+
s = pd.Series(['1', '-3.14', 7])
|
| 36 |
+
res = to_numeric(s)
|
| 37 |
+
tm.assert_series_equal(res, expected)
|
| 38 |
+
|
| 39 |
+
def test_series_numeric(self):
|
| 40 |
+
s = pd.Series([1, 3, 4, 5], index=list('ABCD'), name='XXX')
|
| 41 |
+
res = to_numeric(s)
|
| 42 |
+
tm.assert_series_equal(res, s)
|
| 43 |
+
|
| 44 |
+
s = pd.Series([1., 3., 4., 5.], index=list('ABCD'), name='XXX')
|
| 45 |
+
res = to_numeric(s)
|
| 46 |
+
tm.assert_series_equal(res, s)
|
| 47 |
+
|
| 48 |
+
# bool is regarded as numeric
|
| 49 |
+
s = pd.Series([True, False, True, True],
|
| 50 |
+
index=list('ABCD'), name='XXX')
|
| 51 |
+
res = to_numeric(s)
|
| 52 |
+
tm.assert_series_equal(res, s)
|
| 53 |
+
|
| 54 |
+
def test_error(self):
|
| 55 |
+
s = pd.Series([1, -3.14, 'apple'])
|
| 56 |
+
msg = 'Unable to parse string "apple" at position 2'
|
| 57 |
+
with pytest.raises(ValueError, match=msg):
|
| 58 |
+
to_numeric(s, errors='raise')
|
| 59 |
+
|
| 60 |
+
res = to_numeric(s, errors='ignore')
|
| 61 |
+
expected = pd.Series([1, -3.14, 'apple'])
|
| 62 |
+
tm.assert_series_equal(res, expected)
|
| 63 |
+
|
| 64 |
+
res = to_numeric(s, errors='coerce')
|
| 65 |
+
expected = pd.Series([1, -3.14, np.nan])
|
| 66 |
+
tm.assert_series_equal(res, expected)
|
| 67 |
+
|
| 68 |
+
s = pd.Series(['orange', 1, -3.14, 'apple'])
|
| 69 |
+
msg = 'Unable to parse string "orange" at position 0'
|
| 70 |
+
with pytest.raises(ValueError, match=msg):
|
| 71 |
+
to_numeric(s, errors='raise')
|
| 72 |
+
|
| 73 |
+
def test_error_seen_bool(self):
|
| 74 |
+
s = pd.Series([True, False, 'apple'])
|
| 75 |
+
msg = 'Unable to parse string "apple" at position 2'
|
| 76 |
+
with pytest.raises(ValueError, match=msg):
|
| 77 |
+
to_numeric(s, errors='raise')
|
| 78 |
+
|
| 79 |
+
res = to_numeric(s, errors='ignore')
|
| 80 |
+
expected = pd.Series([True, False, 'apple'])
|
| 81 |
+
tm.assert_series_equal(res, expected)
|
| 82 |
+
|
| 83 |
+
# coerces to float
|
| 84 |
+
res = to_numeric(s, errors='coerce')
|
| 85 |
+
expected = pd.Series([1., 0., np.nan])
|
| 86 |
+
tm.assert_series_equal(res, expected)
|
| 87 |
+
|
| 88 |
+
def test_list(self):
|
| 89 |
+
s = ['1', '-3.14', '7']
|
| 90 |
+
res = to_numeric(s)
|
| 91 |
+
expected = np.array([1, -3.14, 7])
|
| 92 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 93 |
+
|
| 94 |
+
def test_list_numeric(self):
|
| 95 |
+
s = [1, 3, 4, 5]
|
| 96 |
+
res = to_numeric(s)
|
| 97 |
+
tm.assert_numpy_array_equal(res, np.array(s, dtype=np.int64))
|
| 98 |
+
|
| 99 |
+
s = [1., 3., 4., 5.]
|
| 100 |
+
res = to_numeric(s)
|
| 101 |
+
tm.assert_numpy_array_equal(res, np.array(s))
|
| 102 |
+
|
| 103 |
+
# bool is regarded as numeric
|
| 104 |
+
s = [True, False, True, True]
|
| 105 |
+
res = to_numeric(s)
|
| 106 |
+
tm.assert_numpy_array_equal(res, np.array(s))
|
| 107 |
+
|
| 108 |
+
def test_numeric(self):
|
| 109 |
+
s = pd.Series([1, -3.14, 7], dtype='O')
|
| 110 |
+
res = to_numeric(s)
|
| 111 |
+
expected = pd.Series([1, -3.14, 7])
|
| 112 |
+
tm.assert_series_equal(res, expected)
|
| 113 |
+
|
| 114 |
+
s = pd.Series([1, -3.14, 7])
|
| 115 |
+
res = to_numeric(s)
|
| 116 |
+
tm.assert_series_equal(res, expected)
|
| 117 |
+
|
| 118 |
+
# GH 14827
|
| 119 |
+
df = pd.DataFrame(dict(
|
| 120 |
+
a=[1.2, decimal.Decimal(3.14), decimal.Decimal("infinity"), '0.1'],
|
| 121 |
+
b=[1.0, 2.0, 3.0, 4.0],
|
| 122 |
+
))
|
| 123 |
+
expected = pd.DataFrame(dict(
|
| 124 |
+
a=[1.2, 3.14, np.inf, 0.1],
|
| 125 |
+
b=[1.0, 2.0, 3.0, 4.0],
|
| 126 |
+
))
|
| 127 |
+
|
| 128 |
+
# Test to_numeric over one column
|
| 129 |
+
df_copy = df.copy()
|
| 130 |
+
df_copy['a'] = df_copy['a'].apply(to_numeric)
|
| 131 |
+
tm.assert_frame_equal(df_copy, expected)
|
| 132 |
+
|
| 133 |
+
# Test to_numeric over multiple columns
|
| 134 |
+
df_copy = df.copy()
|
| 135 |
+
df_copy[['a', 'b']] = df_copy[['a', 'b']].apply(to_numeric)
|
| 136 |
+
tm.assert_frame_equal(df_copy, expected)
|
| 137 |
+
|
| 138 |
+
def test_numeric_lists_and_arrays(self):
|
| 139 |
+
# Test to_numeric with embedded lists and arrays
|
| 140 |
+
df = pd.DataFrame(dict(
|
| 141 |
+
a=[[decimal.Decimal(3.14), 1.0], decimal.Decimal(1.6), 0.1]
|
| 142 |
+
))
|
| 143 |
+
df['a'] = df['a'].apply(to_numeric)
|
| 144 |
+
expected = pd.DataFrame(dict(
|
| 145 |
+
a=[[3.14, 1.0], 1.6, 0.1],
|
| 146 |
+
))
|
| 147 |
+
tm.assert_frame_equal(df, expected)
|
| 148 |
+
|
| 149 |
+
df = pd.DataFrame(dict(
|
| 150 |
+
a=[np.array([decimal.Decimal(3.14), 1.0]), 0.1]
|
| 151 |
+
))
|
| 152 |
+
df['a'] = df['a'].apply(to_numeric)
|
| 153 |
+
expected = pd.DataFrame(dict(
|
| 154 |
+
a=[[3.14, 1.0], 0.1],
|
| 155 |
+
))
|
| 156 |
+
tm.assert_frame_equal(df, expected)
|
| 157 |
+
|
| 158 |
+
def test_all_nan(self):
|
| 159 |
+
s = pd.Series(['a', 'b', 'c'])
|
| 160 |
+
res = to_numeric(s, errors='coerce')
|
| 161 |
+
expected = pd.Series([np.nan, np.nan, np.nan])
|
| 162 |
+
tm.assert_series_equal(res, expected)
|
| 163 |
+
|
| 164 |
+
@pytest.mark.parametrize("errors", [None, "ignore", "raise", "coerce"])
|
| 165 |
+
def test_type_check(self, errors):
|
| 166 |
+
# see gh-11776
|
| 167 |
+
df = pd.DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]})
|
| 168 |
+
kwargs = dict(errors=errors) if errors is not None else dict()
|
| 169 |
+
error_ctx = pytest.raises(TypeError, match="1-d array")
|
| 170 |
+
|
| 171 |
+
with error_ctx:
|
| 172 |
+
to_numeric(df, **kwargs)
|
| 173 |
+
|
| 174 |
+
def test_scalar(self):
|
| 175 |
+
assert pd.to_numeric(1) == 1
|
| 176 |
+
assert pd.to_numeric(1.1) == 1.1
|
| 177 |
+
|
| 178 |
+
assert pd.to_numeric('1') == 1
|
| 179 |
+
assert pd.to_numeric('1.1') == 1.1
|
| 180 |
+
|
| 181 |
+
with pytest.raises(ValueError):
|
| 182 |
+
to_numeric('XX', errors='raise')
|
| 183 |
+
|
| 184 |
+
assert to_numeric('XX', errors='ignore') == 'XX'
|
| 185 |
+
assert np.isnan(to_numeric('XX', errors='coerce'))
|
| 186 |
+
|
| 187 |
+
def test_numeric_dtypes(self):
|
| 188 |
+
idx = pd.Index([1, 2, 3], name='xxx')
|
| 189 |
+
res = pd.to_numeric(idx)
|
| 190 |
+
tm.assert_index_equal(res, idx)
|
| 191 |
+
|
| 192 |
+
res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 193 |
+
tm.assert_series_equal(res, pd.Series(idx, name='xxx'))
|
| 194 |
+
|
| 195 |
+
res = pd.to_numeric(idx.values)
|
| 196 |
+
tm.assert_numpy_array_equal(res, idx.values)
|
| 197 |
+
|
| 198 |
+
idx = pd.Index([1., np.nan, 3., np.nan], name='xxx')
|
| 199 |
+
res = pd.to_numeric(idx)
|
| 200 |
+
tm.assert_index_equal(res, idx)
|
| 201 |
+
|
| 202 |
+
res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 203 |
+
tm.assert_series_equal(res, pd.Series(idx, name='xxx'))
|
| 204 |
+
|
| 205 |
+
res = pd.to_numeric(idx.values)
|
| 206 |
+
tm.assert_numpy_array_equal(res, idx.values)
|
| 207 |
+
|
| 208 |
+
def test_str(self):
|
| 209 |
+
idx = pd.Index(['1', '2', '3'], name='xxx')
|
| 210 |
+
exp = np.array([1, 2, 3], dtype='int64')
|
| 211 |
+
res = pd.to_numeric(idx)
|
| 212 |
+
tm.assert_index_equal(res, pd.Index(exp, name='xxx'))
|
| 213 |
+
|
| 214 |
+
res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 215 |
+
tm.assert_series_equal(res, pd.Series(exp, name='xxx'))
|
| 216 |
+
|
| 217 |
+
res = pd.to_numeric(idx.values)
|
| 218 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 219 |
+
|
| 220 |
+
idx = pd.Index(['1.5', '2.7', '3.4'], name='xxx')
|
| 221 |
+
exp = np.array([1.5, 2.7, 3.4])
|
| 222 |
+
res = pd.to_numeric(idx)
|
| 223 |
+
tm.assert_index_equal(res, pd.Index(exp, name='xxx'))
|
| 224 |
+
|
| 225 |
+
res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 226 |
+
tm.assert_series_equal(res, pd.Series(exp, name='xxx'))
|
| 227 |
+
|
| 228 |
+
res = pd.to_numeric(idx.values)
|
| 229 |
+
tm.assert_numpy_array_equal(res, exp)
|
| 230 |
+
|
| 231 |
+
def test_datetime_like(self, tz_naive_fixture):
|
| 232 |
+
idx = pd.date_range("20130101", periods=3,
|
| 233 |
+
tz=tz_naive_fixture, name="xxx")
|
| 234 |
+
res = pd.to_numeric(idx)
|
| 235 |
+
tm.assert_index_equal(res, pd.Index(idx.asi8, name="xxx"))
|
| 236 |
+
|
| 237 |
+
res = pd.to_numeric(pd.Series(idx, name="xxx"))
|
| 238 |
+
tm.assert_series_equal(res, pd.Series(idx.asi8, name="xxx"))
|
| 239 |
+
|
| 240 |
+
res = pd.to_numeric(idx.values)
|
| 241 |
+
tm.assert_numpy_array_equal(res, idx.asi8)
|
| 242 |
+
|
| 243 |
+
def test_timedelta(self):
|
| 244 |
+
idx = pd.timedelta_range('1 days', periods=3, freq='D', name='xxx')
|
| 245 |
+
res = pd.to_numeric(idx)
|
| 246 |
+
tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx'))
|
| 247 |
+
|
| 248 |
+
res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 249 |
+
tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx'))
|
| 250 |
+
|
| 251 |
+
res = pd.to_numeric(idx.values)
|
| 252 |
+
tm.assert_numpy_array_equal(res, idx.asi8)
|
| 253 |
+
|
| 254 |
+
def test_period(self):
|
| 255 |
+
idx = pd.period_range('2011-01', periods=3, freq='M', name='xxx')
|
| 256 |
+
res = pd.to_numeric(idx)
|
| 257 |
+
tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx'))
|
| 258 |
+
|
| 259 |
+
# TODO: enable when we can support native PeriodDtype
|
| 260 |
+
# res = pd.to_numeric(pd.Series(idx, name='xxx'))
|
| 261 |
+
# tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx'))
|
| 262 |
+
|
| 263 |
+
def test_non_hashable(self):
|
| 264 |
+
# Test for Bug #13324
|
| 265 |
+
s = pd.Series([[10.0, 2], 1.0, 'apple'])
|
| 266 |
+
res = pd.to_numeric(s, errors='coerce')
|
| 267 |
+
tm.assert_series_equal(res, pd.Series([np.nan, 1.0, np.nan]))
|
| 268 |
+
|
| 269 |
+
res = pd.to_numeric(s, errors='ignore')
|
| 270 |
+
tm.assert_series_equal(res, pd.Series([[10.0, 2], 1.0, 'apple']))
|
| 271 |
+
|
| 272 |
+
with pytest.raises(TypeError, match="Invalid object type"):
|
| 273 |
+
pd.to_numeric(s)
|
| 274 |
+
|
| 275 |
+
@pytest.mark.parametrize("data", [
|
| 276 |
+
["1", 2, 3],
|
| 277 |
+
[1, 2, 3],
|
| 278 |
+
np.array(["1970-01-02", "1970-01-03",
|
| 279 |
+
"1970-01-04"], dtype="datetime64[D]")
|
| 280 |
+
])
|
| 281 |
+
def test_downcast_basic(self, data):
|
| 282 |
+
# see gh-13352
|
| 283 |
+
invalid_downcast = "unsigned-integer"
|
| 284 |
+
msg = "invalid downcasting method provided"
|
| 285 |
+
|
| 286 |
+
with pytest.raises(ValueError, match=msg):
|
| 287 |
+
pd.to_numeric(data, downcast=invalid_downcast)
|
| 288 |
+
|
| 289 |
+
expected = np.array([1, 2, 3], dtype=np.int64)
|
| 290 |
+
|
| 291 |
+
# Basic function tests.
|
| 292 |
+
res = pd.to_numeric(data)
|
| 293 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 294 |
+
|
| 295 |
+
res = pd.to_numeric(data, downcast=None)
|
| 296 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 297 |
+
|
| 298 |
+
# Basic dtype support.
|
| 299 |
+
smallest_uint_dtype = np.dtype(np.typecodes["UnsignedInteger"][0])
|
| 300 |
+
|
| 301 |
+
# Support below np.float32 is rare and far between.
|
| 302 |
+
float_32_char = np.dtype(np.float32).char
|
| 303 |
+
smallest_float_dtype = float_32_char
|
| 304 |
+
|
| 305 |
+
expected = np.array([1, 2, 3], dtype=smallest_uint_dtype)
|
| 306 |
+
res = pd.to_numeric(data, downcast="unsigned")
|
| 307 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 308 |
+
|
| 309 |
+
expected = np.array([1, 2, 3], dtype=smallest_float_dtype)
|
| 310 |
+
res = pd.to_numeric(data, downcast="float")
|
| 311 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 312 |
+
|
| 313 |
+
@pytest.mark.parametrize("signed_downcast", ["integer", "signed"])
|
| 314 |
+
@pytest.mark.parametrize("data", [
|
| 315 |
+
["1", 2, 3],
|
| 316 |
+
[1, 2, 3],
|
| 317 |
+
np.array(["1970-01-02", "1970-01-03",
|
| 318 |
+
"1970-01-04"], dtype="datetime64[D]")
|
| 319 |
+
])
|
| 320 |
+
def test_signed_downcast(self, data, signed_downcast):
|
| 321 |
+
# see gh-13352
|
| 322 |
+
smallest_int_dtype = np.dtype(np.typecodes["Integer"][0])
|
| 323 |
+
expected = np.array([1, 2, 3], dtype=smallest_int_dtype)
|
| 324 |
+
|
| 325 |
+
res = pd.to_numeric(data, downcast=signed_downcast)
|
| 326 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 327 |
+
|
| 328 |
+
def test_ignore_downcast_invalid_data(self):
|
| 329 |
+
# If we can't successfully cast the given
|
| 330 |
+
# data to a numeric dtype, do not bother
|
| 331 |
+
# with the downcast parameter.
|
| 332 |
+
data = ["foo", 2, 3]
|
| 333 |
+
expected = np.array(data, dtype=object)
|
| 334 |
+
|
| 335 |
+
res = pd.to_numeric(data, errors="ignore",
|
| 336 |
+
downcast="unsigned")
|
| 337 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 338 |
+
|
| 339 |
+
def test_ignore_downcast_neg_to_unsigned(self):
|
| 340 |
+
# Cannot cast to an unsigned integer
|
| 341 |
+
# because we have a negative number.
|
| 342 |
+
data = ["-1", 2, 3]
|
| 343 |
+
expected = np.array([-1, 2, 3], dtype=np.int64)
|
| 344 |
+
|
| 345 |
+
res = pd.to_numeric(data, downcast="unsigned")
|
| 346 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 347 |
+
|
| 348 |
+
@pytest.mark.parametrize("downcast", ["integer", "signed", "unsigned"])
|
| 349 |
+
@pytest.mark.parametrize("data,expected", [
|
| 350 |
+
(["1.1", 2, 3],
|
| 351 |
+
np.array([1.1, 2, 3], dtype=np.float64)),
|
| 352 |
+
([10000.0, 20000, 3000, 40000.36, 50000, 50000.00],
|
| 353 |
+
np.array([10000.0, 20000, 3000,
|
| 354 |
+
40000.36, 50000, 50000.00], dtype=np.float64))
|
| 355 |
+
])
|
| 356 |
+
def test_ignore_downcast_cannot_convert_float(
|
| 357 |
+
self, data, expected, downcast):
|
| 358 |
+
# Cannot cast to an integer (signed or unsigned)
|
| 359 |
+
# because we have a float number.
|
| 360 |
+
res = pd.to_numeric(data, downcast=downcast)
|
| 361 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 362 |
+
|
| 363 |
+
@pytest.mark.parametrize("downcast,expected_dtype", [
|
| 364 |
+
("integer", np.int16),
|
| 365 |
+
("signed", np.int16),
|
| 366 |
+
("unsigned", np.uint16)
|
| 367 |
+
])
|
| 368 |
+
def test_downcast_not8bit(self, downcast, expected_dtype):
|
| 369 |
+
# the smallest integer dtype need not be np.(u)int8
|
| 370 |
+
data = ["256", 257, 258]
|
| 371 |
+
|
| 372 |
+
expected = np.array([256, 257, 258], dtype=expected_dtype)
|
| 373 |
+
res = pd.to_numeric(data, downcast=downcast)
|
| 374 |
+
tm.assert_numpy_array_equal(res, expected)
|
| 375 |
+
|
| 376 |
+
@pytest.mark.parametrize("dtype,downcast,min_max", [
|
| 377 |
+
("int8", "integer", [iinfo(np.int8).min,
|
| 378 |
+
iinfo(np.int8).max]),
|
| 379 |
+
("int16", "integer", [iinfo(np.int16).min,
|
| 380 |
+
iinfo(np.int16).max]),
|
| 381 |
+
('int32', "integer", [iinfo(np.int32).min,
|
| 382 |
+
iinfo(np.int32).max]),
|
| 383 |
+
('int64', "integer", [iinfo(np.int64).min,
|
| 384 |
+
iinfo(np.int64).max]),
|
| 385 |
+
('uint8', "unsigned", [iinfo(np.uint8).min,
|
| 386 |
+
iinfo(np.uint8).max]),
|
| 387 |
+
('uint16', "unsigned", [iinfo(np.uint16).min,
|
| 388 |
+
iinfo(np.uint16).max]),
|
| 389 |
+
('uint32', "unsigned", [iinfo(np.uint32).min,
|
| 390 |
+
iinfo(np.uint32).max]),
|
| 391 |
+
('uint64', "unsigned", [iinfo(np.uint64).min,
|
| 392 |
+
iinfo(np.uint64).max]),
|
| 393 |
+
('int16', "integer", [iinfo(np.int8).min,
|
| 394 |
+
iinfo(np.int8).max + 1]),
|
| 395 |
+
('int32', "integer", [iinfo(np.int16).min,
|
| 396 |
+
iinfo(np.int16).max + 1]),
|
| 397 |
+
('int64', "integer", [iinfo(np.int32).min,
|
| 398 |
+
iinfo(np.int32).max + 1]),
|
| 399 |
+
('int16', "integer", [iinfo(np.int8).min - 1,
|
| 400 |
+
iinfo(np.int16).max]),
|
| 401 |
+
('int32', "integer", [iinfo(np.int16).min - 1,
|
| 402 |
+
iinfo(np.int32).max]),
|
| 403 |
+
('int64', "integer", [iinfo(np.int32).min - 1,
|
| 404 |
+
iinfo(np.int64).max]),
|
| 405 |
+
('uint16', "unsigned", [iinfo(np.uint8).min,
|
| 406 |
+
iinfo(np.uint8).max + 1]),
|
| 407 |
+
('uint32', "unsigned", [iinfo(np.uint16).min,
|
| 408 |
+
iinfo(np.uint16).max + 1]),
|
| 409 |
+
('uint64', "unsigned", [iinfo(np.uint32).min,
|
| 410 |
+
iinfo(np.uint32).max + 1])
|
| 411 |
+
])
|
| 412 |
+
def test_downcast_limits(self, dtype, downcast, min_max):
|
| 413 |
+
# see gh-14404: test the limits of each downcast.
|
| 414 |
+
series = pd.to_numeric(pd.Series(min_max), downcast=downcast)
|
| 415 |
+
assert series.dtype == dtype
|
| 416 |
+
|
| 417 |
+
def test_coerce_uint64_conflict(self):
|
| 418 |
+
# see gh-17007 and gh-17125
|
| 419 |
+
#
|
| 420 |
+
# Still returns float despite the uint64-nan conflict,
|
| 421 |
+
# which would normally force the casting to object.
|
| 422 |
+
df = pd.DataFrame({"a": [200, 300, "", "NaN", 30000000000000000000]})
|
| 423 |
+
expected = pd.Series([200, 300, np.nan, np.nan,
|
| 424 |
+
30000000000000000000], dtype=float, name="a")
|
| 425 |
+
result = to_numeric(df["a"], errors="coerce")
|
| 426 |
+
tm.assert_series_equal(result, expected)
|
| 427 |
+
|
| 428 |
+
s = pd.Series(["12345678901234567890", "1234567890", "ITEM"])
|
| 429 |
+
expected = pd.Series([12345678901234567890,
|
| 430 |
+
1234567890, np.nan], dtype=float)
|
| 431 |
+
result = to_numeric(s, errors="coerce")
|
| 432 |
+
tm.assert_series_equal(result, expected)
|
| 433 |
+
|
| 434 |
+
# For completeness, check against "ignore" and "raise"
|
| 435 |
+
result = to_numeric(s, errors="ignore")
|
| 436 |
+
tm.assert_series_equal(result, s)
|
| 437 |
+
|
| 438 |
+
msg = "Unable to parse string"
|
| 439 |
+
with pytest.raises(ValueError, match=msg):
|
| 440 |
+
to_numeric(s, errors="raise")
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/__init__.py
ADDED
|
File without changes
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/test_frequencies.py
ADDED
|
@@ -0,0 +1,793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timedelta
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from pandas._libs.tslibs import frequencies as libfrequencies, resolution
|
| 7 |
+
from pandas._libs.tslibs.ccalendar import MONTHS
|
| 8 |
+
from pandas._libs.tslibs.frequencies import (
|
| 9 |
+
INVALID_FREQ_ERR_MSG, FreqGroup, _period_code_map, get_freq, get_freq_code)
|
| 10 |
+
import pandas.compat as compat
|
| 11 |
+
from pandas.compat import is_platform_windows, range
|
| 12 |
+
|
| 13 |
+
from pandas import (
|
| 14 |
+
DatetimeIndex, Index, Series, Timedelta, Timestamp, date_range,
|
| 15 |
+
period_range)
|
| 16 |
+
from pandas.core.tools.datetimes import to_datetime
|
| 17 |
+
import pandas.util.testing as tm
|
| 18 |
+
|
| 19 |
+
import pandas.tseries.frequencies as frequencies
|
| 20 |
+
import pandas.tseries.offsets as offsets
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestToOffset(object):
|
| 24 |
+
|
| 25 |
+
def test_to_offset_multiple(self):
|
| 26 |
+
freqstr = '2h30min'
|
| 27 |
+
freqstr2 = '2h 30min'
|
| 28 |
+
|
| 29 |
+
result = frequencies.to_offset(freqstr)
|
| 30 |
+
assert (result == frequencies.to_offset(freqstr2))
|
| 31 |
+
expected = offsets.Minute(150)
|
| 32 |
+
assert (result == expected)
|
| 33 |
+
|
| 34 |
+
freqstr = '2h30min15s'
|
| 35 |
+
result = frequencies.to_offset(freqstr)
|
| 36 |
+
expected = offsets.Second(150 * 60 + 15)
|
| 37 |
+
assert (result == expected)
|
| 38 |
+
|
| 39 |
+
freqstr = '2h 60min'
|
| 40 |
+
result = frequencies.to_offset(freqstr)
|
| 41 |
+
expected = offsets.Hour(3)
|
| 42 |
+
assert (result == expected)
|
| 43 |
+
|
| 44 |
+
freqstr = '2h 20.5min'
|
| 45 |
+
result = frequencies.to_offset(freqstr)
|
| 46 |
+
expected = offsets.Second(8430)
|
| 47 |
+
assert (result == expected)
|
| 48 |
+
|
| 49 |
+
freqstr = '1.5min'
|
| 50 |
+
result = frequencies.to_offset(freqstr)
|
| 51 |
+
expected = offsets.Second(90)
|
| 52 |
+
assert (result == expected)
|
| 53 |
+
|
| 54 |
+
freqstr = '0.5S'
|
| 55 |
+
result = frequencies.to_offset(freqstr)
|
| 56 |
+
expected = offsets.Milli(500)
|
| 57 |
+
assert (result == expected)
|
| 58 |
+
|
| 59 |
+
freqstr = '15l500u'
|
| 60 |
+
result = frequencies.to_offset(freqstr)
|
| 61 |
+
expected = offsets.Micro(15500)
|
| 62 |
+
assert (result == expected)
|
| 63 |
+
|
| 64 |
+
freqstr = '10s75L'
|
| 65 |
+
result = frequencies.to_offset(freqstr)
|
| 66 |
+
expected = offsets.Milli(10075)
|
| 67 |
+
assert (result == expected)
|
| 68 |
+
|
| 69 |
+
freqstr = '1s0.25ms'
|
| 70 |
+
result = frequencies.to_offset(freqstr)
|
| 71 |
+
expected = offsets.Micro(1000250)
|
| 72 |
+
assert (result == expected)
|
| 73 |
+
|
| 74 |
+
freqstr = '1s0.25L'
|
| 75 |
+
result = frequencies.to_offset(freqstr)
|
| 76 |
+
expected = offsets.Micro(1000250)
|
| 77 |
+
assert (result == expected)
|
| 78 |
+
|
| 79 |
+
freqstr = '2800N'
|
| 80 |
+
result = frequencies.to_offset(freqstr)
|
| 81 |
+
expected = offsets.Nano(2800)
|
| 82 |
+
assert (result == expected)
|
| 83 |
+
|
| 84 |
+
freqstr = '2SM'
|
| 85 |
+
result = frequencies.to_offset(freqstr)
|
| 86 |
+
expected = offsets.SemiMonthEnd(2)
|
| 87 |
+
assert (result == expected)
|
| 88 |
+
|
| 89 |
+
freqstr = '2SM-16'
|
| 90 |
+
result = frequencies.to_offset(freqstr)
|
| 91 |
+
expected = offsets.SemiMonthEnd(2, day_of_month=16)
|
| 92 |
+
assert (result == expected)
|
| 93 |
+
|
| 94 |
+
freqstr = '2SMS-14'
|
| 95 |
+
result = frequencies.to_offset(freqstr)
|
| 96 |
+
expected = offsets.SemiMonthBegin(2, day_of_month=14)
|
| 97 |
+
assert (result == expected)
|
| 98 |
+
|
| 99 |
+
freqstr = '2SMS-15'
|
| 100 |
+
result = frequencies.to_offset(freqstr)
|
| 101 |
+
expected = offsets.SemiMonthBegin(2)
|
| 102 |
+
assert (result == expected)
|
| 103 |
+
|
| 104 |
+
# malformed
|
| 105 |
+
with pytest.raises(ValueError, match='Invalid frequency: 2h20m'):
|
| 106 |
+
frequencies.to_offset('2h20m')
|
| 107 |
+
|
| 108 |
+
def test_to_offset_negative(self):
|
| 109 |
+
freqstr = '-1S'
|
| 110 |
+
result = frequencies.to_offset(freqstr)
|
| 111 |
+
assert (result.n == -1)
|
| 112 |
+
|
| 113 |
+
freqstr = '-5min10s'
|
| 114 |
+
result = frequencies.to_offset(freqstr)
|
| 115 |
+
assert (result.n == -310)
|
| 116 |
+
|
| 117 |
+
freqstr = '-2SM'
|
| 118 |
+
result = frequencies.to_offset(freqstr)
|
| 119 |
+
assert (result.n == -2)
|
| 120 |
+
|
| 121 |
+
freqstr = '-1SMS'
|
| 122 |
+
result = frequencies.to_offset(freqstr)
|
| 123 |
+
assert (result.n == -1)
|
| 124 |
+
|
| 125 |
+
def test_to_offset_invalid(self):
|
| 126 |
+
# GH 13930
|
| 127 |
+
with pytest.raises(ValueError, match='Invalid frequency: U1'):
|
| 128 |
+
frequencies.to_offset('U1')
|
| 129 |
+
with pytest.raises(ValueError, match='Invalid frequency: -U'):
|
| 130 |
+
frequencies.to_offset('-U')
|
| 131 |
+
with pytest.raises(ValueError, match='Invalid frequency: 3U1'):
|
| 132 |
+
frequencies.to_offset('3U1')
|
| 133 |
+
with pytest.raises(ValueError, match='Invalid frequency: -2-3U'):
|
| 134 |
+
frequencies.to_offset('-2-3U')
|
| 135 |
+
with pytest.raises(ValueError, match='Invalid frequency: -2D:3H'):
|
| 136 |
+
frequencies.to_offset('-2D:3H')
|
| 137 |
+
with pytest.raises(ValueError, match='Invalid frequency: 1.5.0S'):
|
| 138 |
+
frequencies.to_offset('1.5.0S')
|
| 139 |
+
|
| 140 |
+
# split offsets with spaces are valid
|
| 141 |
+
assert frequencies.to_offset('2D 3H') == offsets.Hour(51)
|
| 142 |
+
assert frequencies.to_offset('2 D3 H') == offsets.Hour(51)
|
| 143 |
+
assert frequencies.to_offset('2 D 3 H') == offsets.Hour(51)
|
| 144 |
+
assert frequencies.to_offset(' 2 D 3 H ') == offsets.Hour(51)
|
| 145 |
+
assert frequencies.to_offset(' H ') == offsets.Hour()
|
| 146 |
+
assert frequencies.to_offset(' 3 H ') == offsets.Hour(3)
|
| 147 |
+
|
| 148 |
+
# special cases
|
| 149 |
+
assert frequencies.to_offset('2SMS-15') == offsets.SemiMonthBegin(2)
|
| 150 |
+
with pytest.raises(ValueError, match='Invalid frequency: 2SMS-15-15'):
|
| 151 |
+
frequencies.to_offset('2SMS-15-15')
|
| 152 |
+
with pytest.raises(ValueError, match='Invalid frequency: 2SMS-15D'):
|
| 153 |
+
frequencies.to_offset('2SMS-15D')
|
| 154 |
+
|
| 155 |
+
def test_to_offset_leading_zero(self):
|
| 156 |
+
freqstr = '00H 00T 01S'
|
| 157 |
+
result = frequencies.to_offset(freqstr)
|
| 158 |
+
assert (result.n == 1)
|
| 159 |
+
|
| 160 |
+
freqstr = '-00H 03T 14S'
|
| 161 |
+
result = frequencies.to_offset(freqstr)
|
| 162 |
+
assert (result.n == -194)
|
| 163 |
+
|
| 164 |
+
def test_to_offset_leading_plus(self):
|
| 165 |
+
freqstr = '+1d'
|
| 166 |
+
result = frequencies.to_offset(freqstr)
|
| 167 |
+
assert (result.n == 1)
|
| 168 |
+
|
| 169 |
+
freqstr = '+2h30min'
|
| 170 |
+
result = frequencies.to_offset(freqstr)
|
| 171 |
+
assert (result.n == 150)
|
| 172 |
+
|
| 173 |
+
for bad_freq in ['+-1d', '-+1h', '+1', '-7', '+d', '-m']:
|
| 174 |
+
with pytest.raises(ValueError, match='Invalid frequency:'):
|
| 175 |
+
frequencies.to_offset(bad_freq)
|
| 176 |
+
|
| 177 |
+
def test_to_offset_pd_timedelta(self):
|
| 178 |
+
# Tests for #9064
|
| 179 |
+
td = Timedelta(days=1, seconds=1)
|
| 180 |
+
result = frequencies.to_offset(td)
|
| 181 |
+
expected = offsets.Second(86401)
|
| 182 |
+
assert (expected == result)
|
| 183 |
+
|
| 184 |
+
td = Timedelta(days=-1, seconds=1)
|
| 185 |
+
result = frequencies.to_offset(td)
|
| 186 |
+
expected = offsets.Second(-86399)
|
| 187 |
+
assert (expected == result)
|
| 188 |
+
|
| 189 |
+
td = Timedelta(hours=1, minutes=10)
|
| 190 |
+
result = frequencies.to_offset(td)
|
| 191 |
+
expected = offsets.Minute(70)
|
| 192 |
+
assert (expected == result)
|
| 193 |
+
|
| 194 |
+
td = Timedelta(hours=1, minutes=-10)
|
| 195 |
+
result = frequencies.to_offset(td)
|
| 196 |
+
expected = offsets.Minute(50)
|
| 197 |
+
assert (expected == result)
|
| 198 |
+
|
| 199 |
+
td = Timedelta(weeks=1)
|
| 200 |
+
result = frequencies.to_offset(td)
|
| 201 |
+
expected = offsets.Day(7)
|
| 202 |
+
assert (expected == result)
|
| 203 |
+
|
| 204 |
+
td1 = Timedelta(hours=1)
|
| 205 |
+
result1 = frequencies.to_offset(td1)
|
| 206 |
+
result2 = frequencies.to_offset('60min')
|
| 207 |
+
assert (result1 == result2)
|
| 208 |
+
|
| 209 |
+
td = Timedelta(microseconds=1)
|
| 210 |
+
result = frequencies.to_offset(td)
|
| 211 |
+
expected = offsets.Micro(1)
|
| 212 |
+
assert (expected == result)
|
| 213 |
+
|
| 214 |
+
td = Timedelta(microseconds=0)
|
| 215 |
+
pytest.raises(ValueError, lambda: frequencies.to_offset(td))
|
| 216 |
+
|
| 217 |
+
def test_anchored_shortcuts(self):
|
| 218 |
+
result = frequencies.to_offset('W')
|
| 219 |
+
expected = frequencies.to_offset('W-SUN')
|
| 220 |
+
assert (result == expected)
|
| 221 |
+
|
| 222 |
+
result1 = frequencies.to_offset('Q')
|
| 223 |
+
result2 = frequencies.to_offset('Q-DEC')
|
| 224 |
+
expected = offsets.QuarterEnd(startingMonth=12)
|
| 225 |
+
assert (result1 == expected)
|
| 226 |
+
assert (result2 == expected)
|
| 227 |
+
|
| 228 |
+
result1 = frequencies.to_offset('Q-MAY')
|
| 229 |
+
expected = offsets.QuarterEnd(startingMonth=5)
|
| 230 |
+
assert (result1 == expected)
|
| 231 |
+
|
| 232 |
+
result1 = frequencies.to_offset('SM')
|
| 233 |
+
result2 = frequencies.to_offset('SM-15')
|
| 234 |
+
expected = offsets.SemiMonthEnd(day_of_month=15)
|
| 235 |
+
assert (result1 == expected)
|
| 236 |
+
assert (result2 == expected)
|
| 237 |
+
|
| 238 |
+
result = frequencies.to_offset('SM-1')
|
| 239 |
+
expected = offsets.SemiMonthEnd(day_of_month=1)
|
| 240 |
+
assert (result == expected)
|
| 241 |
+
|
| 242 |
+
result = frequencies.to_offset('SM-27')
|
| 243 |
+
expected = offsets.SemiMonthEnd(day_of_month=27)
|
| 244 |
+
assert (result == expected)
|
| 245 |
+
|
| 246 |
+
result = frequencies.to_offset('SMS-2')
|
| 247 |
+
expected = offsets.SemiMonthBegin(day_of_month=2)
|
| 248 |
+
assert (result == expected)
|
| 249 |
+
|
| 250 |
+
result = frequencies.to_offset('SMS-27')
|
| 251 |
+
expected = offsets.SemiMonthBegin(day_of_month=27)
|
| 252 |
+
assert (result == expected)
|
| 253 |
+
|
| 254 |
+
# ensure invalid cases fail as expected
|
| 255 |
+
invalid_anchors = ['SM-0', 'SM-28', 'SM-29',
|
| 256 |
+
'SM-FOO', 'BSM', 'SM--1',
|
| 257 |
+
'SMS-1', 'SMS-28', 'SMS-30',
|
| 258 |
+
'SMS-BAR', 'SMS-BYR' 'BSMS',
|
| 259 |
+
'SMS--2']
|
| 260 |
+
for invalid_anchor in invalid_anchors:
|
| 261 |
+
with pytest.raises(ValueError, match='Invalid frequency: '):
|
| 262 |
+
frequencies.to_offset(invalid_anchor)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def test_ms_vs_MS():
|
| 266 |
+
left = frequencies.get_offset('ms')
|
| 267 |
+
right = frequencies.get_offset('MS')
|
| 268 |
+
assert left == offsets.Milli()
|
| 269 |
+
assert right == offsets.MonthBegin()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_rule_aliases():
|
| 273 |
+
rule = frequencies.to_offset('10us')
|
| 274 |
+
assert rule == offsets.Micro(10)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class TestFrequencyCode(object):
|
| 278 |
+
|
| 279 |
+
def test_freq_code(self):
|
| 280 |
+
assert get_freq('A') == 1000
|
| 281 |
+
assert get_freq('3A') == 1000
|
| 282 |
+
assert get_freq('-1A') == 1000
|
| 283 |
+
|
| 284 |
+
assert get_freq('Y') == 1000
|
| 285 |
+
assert get_freq('3Y') == 1000
|
| 286 |
+
assert get_freq('-1Y') == 1000
|
| 287 |
+
|
| 288 |
+
assert get_freq('W') == 4000
|
| 289 |
+
assert get_freq('W-MON') == 4001
|
| 290 |
+
assert get_freq('W-FRI') == 4005
|
| 291 |
+
|
| 292 |
+
for freqstr, code in compat.iteritems(_period_code_map):
|
| 293 |
+
result = get_freq(freqstr)
|
| 294 |
+
assert result == code
|
| 295 |
+
|
| 296 |
+
result = resolution.get_freq_group(freqstr)
|
| 297 |
+
assert result == code // 1000 * 1000
|
| 298 |
+
|
| 299 |
+
result = resolution.get_freq_group(code)
|
| 300 |
+
assert result == code // 1000 * 1000
|
| 301 |
+
|
| 302 |
+
def test_freq_group(self):
|
| 303 |
+
assert resolution.get_freq_group('A') == 1000
|
| 304 |
+
assert resolution.get_freq_group('3A') == 1000
|
| 305 |
+
assert resolution.get_freq_group('-1A') == 1000
|
| 306 |
+
assert resolution.get_freq_group('A-JAN') == 1000
|
| 307 |
+
assert resolution.get_freq_group('A-MAY') == 1000
|
| 308 |
+
|
| 309 |
+
assert resolution.get_freq_group('Y') == 1000
|
| 310 |
+
assert resolution.get_freq_group('3Y') == 1000
|
| 311 |
+
assert resolution.get_freq_group('-1Y') == 1000
|
| 312 |
+
assert resolution.get_freq_group('Y-JAN') == 1000
|
| 313 |
+
assert resolution.get_freq_group('Y-MAY') == 1000
|
| 314 |
+
|
| 315 |
+
assert resolution.get_freq_group(offsets.YearEnd()) == 1000
|
| 316 |
+
assert resolution.get_freq_group(offsets.YearEnd(month=1)) == 1000
|
| 317 |
+
assert resolution.get_freq_group(offsets.YearEnd(month=5)) == 1000
|
| 318 |
+
|
| 319 |
+
assert resolution.get_freq_group('W') == 4000
|
| 320 |
+
assert resolution.get_freq_group('W-MON') == 4000
|
| 321 |
+
assert resolution.get_freq_group('W-FRI') == 4000
|
| 322 |
+
assert resolution.get_freq_group(offsets.Week()) == 4000
|
| 323 |
+
assert resolution.get_freq_group(offsets.Week(weekday=1)) == 4000
|
| 324 |
+
assert resolution.get_freq_group(offsets.Week(weekday=5)) == 4000
|
| 325 |
+
|
| 326 |
+
def test_get_to_timestamp_base(self):
|
| 327 |
+
tsb = libfrequencies.get_to_timestamp_base
|
| 328 |
+
|
| 329 |
+
assert (tsb(get_freq_code('D')[0]) ==
|
| 330 |
+
get_freq_code('D')[0])
|
| 331 |
+
assert (tsb(get_freq_code('W')[0]) ==
|
| 332 |
+
get_freq_code('D')[0])
|
| 333 |
+
assert (tsb(get_freq_code('M')[0]) ==
|
| 334 |
+
get_freq_code('D')[0])
|
| 335 |
+
|
| 336 |
+
assert (tsb(get_freq_code('S')[0]) ==
|
| 337 |
+
get_freq_code('S')[0])
|
| 338 |
+
assert (tsb(get_freq_code('T')[0]) ==
|
| 339 |
+
get_freq_code('S')[0])
|
| 340 |
+
assert (tsb(get_freq_code('H')[0]) ==
|
| 341 |
+
get_freq_code('S')[0])
|
| 342 |
+
|
| 343 |
+
def test_freq_to_reso(self):
|
| 344 |
+
Reso = resolution.Resolution
|
| 345 |
+
|
| 346 |
+
assert Reso.get_str_from_freq('A') == 'year'
|
| 347 |
+
assert Reso.get_str_from_freq('Q') == 'quarter'
|
| 348 |
+
assert Reso.get_str_from_freq('M') == 'month'
|
| 349 |
+
assert Reso.get_str_from_freq('D') == 'day'
|
| 350 |
+
assert Reso.get_str_from_freq('H') == 'hour'
|
| 351 |
+
assert Reso.get_str_from_freq('T') == 'minute'
|
| 352 |
+
assert Reso.get_str_from_freq('S') == 'second'
|
| 353 |
+
assert Reso.get_str_from_freq('L') == 'millisecond'
|
| 354 |
+
assert Reso.get_str_from_freq('U') == 'microsecond'
|
| 355 |
+
assert Reso.get_str_from_freq('N') == 'nanosecond'
|
| 356 |
+
|
| 357 |
+
for freq in ['A', 'Q', 'M', 'D', 'H', 'T', 'S', 'L', 'U', 'N']:
|
| 358 |
+
# check roundtrip
|
| 359 |
+
result = Reso.get_freq(Reso.get_str_from_freq(freq))
|
| 360 |
+
assert freq == result
|
| 361 |
+
|
| 362 |
+
for freq in ['D', 'H', 'T', 'S', 'L', 'U']:
|
| 363 |
+
result = Reso.get_freq(Reso.get_str(Reso.get_reso_from_freq(freq)))
|
| 364 |
+
assert freq == result
|
| 365 |
+
|
| 366 |
+
def test_resolution_bumping(self):
|
| 367 |
+
# see gh-14378
|
| 368 |
+
Reso = resolution.Resolution
|
| 369 |
+
|
| 370 |
+
assert Reso.get_stride_from_decimal(1.5, 'T') == (90, 'S')
|
| 371 |
+
assert Reso.get_stride_from_decimal(62.4, 'T') == (3744, 'S')
|
| 372 |
+
assert Reso.get_stride_from_decimal(1.04, 'H') == (3744, 'S')
|
| 373 |
+
assert Reso.get_stride_from_decimal(1, 'D') == (1, 'D')
|
| 374 |
+
assert (Reso.get_stride_from_decimal(0.342931, 'H') ==
|
| 375 |
+
(1234551600, 'U'))
|
| 376 |
+
assert Reso.get_stride_from_decimal(1.2345, 'D') == (106660800, 'L')
|
| 377 |
+
|
| 378 |
+
with pytest.raises(ValueError):
|
| 379 |
+
Reso.get_stride_from_decimal(0.5, 'N')
|
| 380 |
+
|
| 381 |
+
# too much precision in the input can prevent
|
| 382 |
+
with pytest.raises(ValueError):
|
| 383 |
+
Reso.get_stride_from_decimal(0.3429324798798269273987982, 'H')
|
| 384 |
+
|
| 385 |
+
def test_get_freq_code(self):
|
| 386 |
+
# frequency str
|
| 387 |
+
assert (get_freq_code('A') ==
|
| 388 |
+
(get_freq('A'), 1))
|
| 389 |
+
assert (get_freq_code('3D') ==
|
| 390 |
+
(get_freq('D'), 3))
|
| 391 |
+
assert (get_freq_code('-2M') ==
|
| 392 |
+
(get_freq('M'), -2))
|
| 393 |
+
|
| 394 |
+
# tuple
|
| 395 |
+
assert (get_freq_code(('D', 1)) ==
|
| 396 |
+
(get_freq('D'), 1))
|
| 397 |
+
assert (get_freq_code(('A', 3)) ==
|
| 398 |
+
(get_freq('A'), 3))
|
| 399 |
+
assert (get_freq_code(('M', -2)) ==
|
| 400 |
+
(get_freq('M'), -2))
|
| 401 |
+
|
| 402 |
+
# numeric tuple
|
| 403 |
+
assert get_freq_code((1000, 1)) == (1000, 1)
|
| 404 |
+
|
| 405 |
+
# offsets
|
| 406 |
+
assert (get_freq_code(offsets.Day()) ==
|
| 407 |
+
(get_freq('D'), 1))
|
| 408 |
+
assert (get_freq_code(offsets.Day(3)) ==
|
| 409 |
+
(get_freq('D'), 3))
|
| 410 |
+
assert (get_freq_code(offsets.Day(-2)) ==
|
| 411 |
+
(get_freq('D'), -2))
|
| 412 |
+
|
| 413 |
+
assert (get_freq_code(offsets.MonthEnd()) ==
|
| 414 |
+
(get_freq('M'), 1))
|
| 415 |
+
assert (get_freq_code(offsets.MonthEnd(3)) ==
|
| 416 |
+
(get_freq('M'), 3))
|
| 417 |
+
assert (get_freq_code(offsets.MonthEnd(-2)) ==
|
| 418 |
+
(get_freq('M'), -2))
|
| 419 |
+
|
| 420 |
+
assert (get_freq_code(offsets.Week()) ==
|
| 421 |
+
(get_freq('W'), 1))
|
| 422 |
+
assert (get_freq_code(offsets.Week(3)) ==
|
| 423 |
+
(get_freq('W'), 3))
|
| 424 |
+
assert (get_freq_code(offsets.Week(-2)) ==
|
| 425 |
+
(get_freq('W'), -2))
|
| 426 |
+
|
| 427 |
+
# Monday is weekday=0
|
| 428 |
+
assert (get_freq_code(offsets.Week(weekday=1)) ==
|
| 429 |
+
(get_freq('W-TUE'), 1))
|
| 430 |
+
assert (get_freq_code(offsets.Week(3, weekday=0)) ==
|
| 431 |
+
(get_freq('W-MON'), 3))
|
| 432 |
+
assert (get_freq_code(offsets.Week(-2, weekday=4)) ==
|
| 433 |
+
(get_freq('W-FRI'), -2))
|
| 434 |
+
|
| 435 |
+
def test_frequency_misc(self):
|
| 436 |
+
assert (resolution.get_freq_group('T') ==
|
| 437 |
+
FreqGroup.FR_MIN)
|
| 438 |
+
|
| 439 |
+
code, stride = get_freq_code(offsets.Hour())
|
| 440 |
+
assert code == FreqGroup.FR_HR
|
| 441 |
+
|
| 442 |
+
code, stride = get_freq_code((5, 'T'))
|
| 443 |
+
assert code == FreqGroup.FR_MIN
|
| 444 |
+
assert stride == 5
|
| 445 |
+
|
| 446 |
+
offset = offsets.Hour()
|
| 447 |
+
result = frequencies.to_offset(offset)
|
| 448 |
+
assert result == offset
|
| 449 |
+
|
| 450 |
+
result = frequencies.to_offset((5, 'T'))
|
| 451 |
+
expected = offsets.Minute(5)
|
| 452 |
+
assert result == expected
|
| 453 |
+
|
| 454 |
+
with pytest.raises(ValueError, match='Invalid frequency'):
|
| 455 |
+
get_freq_code((5, 'baz'))
|
| 456 |
+
|
| 457 |
+
with pytest.raises(ValueError, match='Invalid frequency'):
|
| 458 |
+
frequencies.to_offset('100foo')
|
| 459 |
+
|
| 460 |
+
with pytest.raises(ValueError, match='Could not evaluate'):
|
| 461 |
+
frequencies.to_offset(('', ''))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
_dti = DatetimeIndex
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class TestFrequencyInference(object):
|
| 468 |
+
|
| 469 |
+
def test_raise_if_period_index(self):
|
| 470 |
+
index = period_range(start="1/1/1990", periods=20, freq="M")
|
| 471 |
+
pytest.raises(TypeError, frequencies.infer_freq, index)
|
| 472 |
+
|
| 473 |
+
def test_raise_if_too_few(self):
|
| 474 |
+
index = _dti(['12/31/1998', '1/3/1999'])
|
| 475 |
+
pytest.raises(ValueError, frequencies.infer_freq, index)
|
| 476 |
+
|
| 477 |
+
def test_business_daily(self):
|
| 478 |
+
index = _dti(['01/01/1999', '1/4/1999', '1/5/1999'])
|
| 479 |
+
assert frequencies.infer_freq(index) == 'B'
|
| 480 |
+
|
| 481 |
+
def test_business_daily_look_alike(self):
|
| 482 |
+
# GH 16624, do not infer 'B' when 'weekend' (2-day gap) in wrong place
|
| 483 |
+
index = _dti(['12/31/1998', '1/3/1999', '1/4/1999'])
|
| 484 |
+
assert frequencies.infer_freq(index) is None
|
| 485 |
+
|
| 486 |
+
def test_day(self):
|
| 487 |
+
self._check_tick(timedelta(1), 'D')
|
| 488 |
+
|
| 489 |
+
def test_day_corner(self):
|
| 490 |
+
index = _dti(['1/1/2000', '1/2/2000', '1/3/2000'])
|
| 491 |
+
assert frequencies.infer_freq(index) == 'D'
|
| 492 |
+
|
| 493 |
+
def test_non_datetimeindex(self):
|
| 494 |
+
dates = to_datetime(['1/1/2000', '1/2/2000', '1/3/2000'])
|
| 495 |
+
assert frequencies.infer_freq(dates) == 'D'
|
| 496 |
+
|
| 497 |
+
def test_hour(self):
|
| 498 |
+
self._check_tick(timedelta(hours=1), 'H')
|
| 499 |
+
|
| 500 |
+
def test_minute(self):
|
| 501 |
+
self._check_tick(timedelta(minutes=1), 'T')
|
| 502 |
+
|
| 503 |
+
def test_second(self):
|
| 504 |
+
self._check_tick(timedelta(seconds=1), 'S')
|
| 505 |
+
|
| 506 |
+
def test_millisecond(self):
|
| 507 |
+
self._check_tick(timedelta(microseconds=1000), 'L')
|
| 508 |
+
|
| 509 |
+
def test_microsecond(self):
|
| 510 |
+
self._check_tick(timedelta(microseconds=1), 'U')
|
| 511 |
+
|
| 512 |
+
def test_nanosecond(self):
|
| 513 |
+
self._check_tick(np.timedelta64(1, 'ns'), 'N')
|
| 514 |
+
|
| 515 |
+
def _check_tick(self, base_delta, code):
|
| 516 |
+
b = Timestamp(datetime.now())
|
| 517 |
+
for i in range(1, 5):
|
| 518 |
+
inc = base_delta * i
|
| 519 |
+
index = _dti([b + inc * j for j in range(3)])
|
| 520 |
+
if i > 1:
|
| 521 |
+
exp_freq = '%d%s' % (i, code)
|
| 522 |
+
else:
|
| 523 |
+
exp_freq = code
|
| 524 |
+
assert frequencies.infer_freq(index) == exp_freq
|
| 525 |
+
|
| 526 |
+
index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range(
|
| 527 |
+
3)])
|
| 528 |
+
assert frequencies.infer_freq(index) is None
|
| 529 |
+
|
| 530 |
+
index = _dti([b + base_delta * j for j in range(3)] + [b + base_delta *
|
| 531 |
+
7])
|
| 532 |
+
|
| 533 |
+
assert frequencies.infer_freq(index) is None
|
| 534 |
+
|
| 535 |
+
def test_weekly(self):
|
| 536 |
+
days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
|
| 537 |
+
|
| 538 |
+
for day in days:
|
| 539 |
+
self._check_generated_range('1/1/2000', 'W-%s' % day)
|
| 540 |
+
|
| 541 |
+
def test_week_of_month(self):
|
| 542 |
+
days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
|
| 543 |
+
|
| 544 |
+
for day in days:
|
| 545 |
+
for i in range(1, 5):
|
| 546 |
+
self._check_generated_range('1/1/2000', 'WOM-%d%s' % (i, day))
|
| 547 |
+
|
| 548 |
+
def test_fifth_week_of_month(self):
|
| 549 |
+
# Only supports freq up to WOM-4. See #9425
|
| 550 |
+
func = lambda: date_range('2014-01-01', freq='WOM-5MON')
|
| 551 |
+
pytest.raises(ValueError, func)
|
| 552 |
+
|
| 553 |
+
def test_fifth_week_of_month_infer(self):
|
| 554 |
+
# Only attempts to infer up to WOM-4. See #9425
|
| 555 |
+
index = DatetimeIndex(["2014-03-31", "2014-06-30", "2015-03-30"])
|
| 556 |
+
assert frequencies.infer_freq(index) is None
|
| 557 |
+
|
| 558 |
+
def test_week_of_month_fake(self):
|
| 559 |
+
# All of these dates are on same day of week and are 4 or 5 weeks apart
|
| 560 |
+
index = DatetimeIndex(["2013-08-27", "2013-10-01", "2013-10-29",
|
| 561 |
+
"2013-11-26"])
|
| 562 |
+
assert frequencies.infer_freq(index) != 'WOM-4TUE'
|
| 563 |
+
|
| 564 |
+
def test_monthly(self):
|
| 565 |
+
self._check_generated_range('1/1/2000', 'M')
|
| 566 |
+
|
| 567 |
+
def test_monthly_ambiguous(self):
|
| 568 |
+
rng = _dti(['1/31/2000', '2/29/2000', '3/31/2000'])
|
| 569 |
+
assert rng.inferred_freq == 'M'
|
| 570 |
+
|
| 571 |
+
def test_business_monthly(self):
|
| 572 |
+
self._check_generated_range('1/1/2000', 'BM')
|
| 573 |
+
|
| 574 |
+
def test_business_start_monthly(self):
|
| 575 |
+
self._check_generated_range('1/1/2000', 'BMS')
|
| 576 |
+
|
| 577 |
+
def test_quarterly(self):
|
| 578 |
+
for month in ['JAN', 'FEB', 'MAR']:
|
| 579 |
+
self._check_generated_range('1/1/2000', 'Q-%s' % month)
|
| 580 |
+
|
| 581 |
+
def test_annual(self):
|
| 582 |
+
for month in MONTHS:
|
| 583 |
+
self._check_generated_range('1/1/2000', 'A-%s' % month)
|
| 584 |
+
|
| 585 |
+
def test_business_annual(self):
|
| 586 |
+
for month in MONTHS:
|
| 587 |
+
self._check_generated_range('1/1/2000', 'BA-%s' % month)
|
| 588 |
+
|
| 589 |
+
def test_annual_ambiguous(self):
|
| 590 |
+
rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
|
| 591 |
+
assert rng.inferred_freq == 'A-JAN'
|
| 592 |
+
|
| 593 |
+
def _check_generated_range(self, start, freq):
|
| 594 |
+
freq = freq.upper()
|
| 595 |
+
|
| 596 |
+
gen = date_range(start, periods=7, freq=freq)
|
| 597 |
+
index = _dti(gen.values)
|
| 598 |
+
if not freq.startswith('Q-'):
|
| 599 |
+
assert frequencies.infer_freq(index) == gen.freqstr
|
| 600 |
+
else:
|
| 601 |
+
inf_freq = frequencies.infer_freq(index)
|
| 602 |
+
is_dec_range = inf_freq == 'Q-DEC' and gen.freqstr in (
|
| 603 |
+
'Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')
|
| 604 |
+
is_nov_range = inf_freq == 'Q-NOV' and gen.freqstr in (
|
| 605 |
+
'Q-NOV', 'Q-AUG', 'Q-MAY', 'Q-FEB')
|
| 606 |
+
is_oct_range = inf_freq == 'Q-OCT' and gen.freqstr in (
|
| 607 |
+
'Q-OCT', 'Q-JUL', 'Q-APR', 'Q-JAN')
|
| 608 |
+
assert is_dec_range or is_nov_range or is_oct_range
|
| 609 |
+
|
| 610 |
+
gen = date_range(start, periods=5, freq=freq)
|
| 611 |
+
index = _dti(gen.values)
|
| 612 |
+
|
| 613 |
+
if not freq.startswith('Q-'):
|
| 614 |
+
assert frequencies.infer_freq(index) == gen.freqstr
|
| 615 |
+
else:
|
| 616 |
+
inf_freq = frequencies.infer_freq(index)
|
| 617 |
+
is_dec_range = inf_freq == 'Q-DEC' and gen.freqstr in (
|
| 618 |
+
'Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')
|
| 619 |
+
is_nov_range = inf_freq == 'Q-NOV' and gen.freqstr in (
|
| 620 |
+
'Q-NOV', 'Q-AUG', 'Q-MAY', 'Q-FEB')
|
| 621 |
+
is_oct_range = inf_freq == 'Q-OCT' and gen.freqstr in (
|
| 622 |
+
'Q-OCT', 'Q-JUL', 'Q-APR', 'Q-JAN')
|
| 623 |
+
|
| 624 |
+
assert is_dec_range or is_nov_range or is_oct_range
|
| 625 |
+
|
| 626 |
+
def test_infer_freq(self):
|
| 627 |
+
rng = period_range('1959Q2', '2009Q3', freq='Q')
|
| 628 |
+
rng = Index(rng.to_timestamp('D', how='e').astype(object))
|
| 629 |
+
assert rng.inferred_freq == 'Q-DEC'
|
| 630 |
+
|
| 631 |
+
rng = period_range('1959Q2', '2009Q3', freq='Q-NOV')
|
| 632 |
+
rng = Index(rng.to_timestamp('D', how='e').astype(object))
|
| 633 |
+
assert rng.inferred_freq == 'Q-NOV'
|
| 634 |
+
|
| 635 |
+
rng = period_range('1959Q2', '2009Q3', freq='Q-OCT')
|
| 636 |
+
rng = Index(rng.to_timestamp('D', how='e').astype(object))
|
| 637 |
+
assert rng.inferred_freq == 'Q-OCT'
|
| 638 |
+
|
| 639 |
+
def test_infer_freq_tz(self):
|
| 640 |
+
|
| 641 |
+
freqs = {'AS-JAN':
|
| 642 |
+
['2009-01-01', '2010-01-01', '2011-01-01', '2012-01-01'],
|
| 643 |
+
'Q-OCT':
|
| 644 |
+
['2009-01-31', '2009-04-30', '2009-07-31', '2009-10-31'],
|
| 645 |
+
'M': ['2010-11-30', '2010-12-31', '2011-01-31', '2011-02-28'],
|
| 646 |
+
'W-SAT':
|
| 647 |
+
['2010-12-25', '2011-01-01', '2011-01-08', '2011-01-15'],
|
| 648 |
+
'D': ['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04'],
|
| 649 |
+
'H': ['2011-12-31 22:00', '2011-12-31 23:00',
|
| 650 |
+
'2012-01-01 00:00', '2012-01-01 01:00']}
|
| 651 |
+
|
| 652 |
+
# GH 7310
|
| 653 |
+
for tz in [None, 'Australia/Sydney', 'Asia/Tokyo', 'Europe/Paris',
|
| 654 |
+
'US/Pacific', 'US/Eastern']:
|
| 655 |
+
for expected, dates in compat.iteritems(freqs):
|
| 656 |
+
idx = DatetimeIndex(dates, tz=tz)
|
| 657 |
+
assert idx.inferred_freq == expected
|
| 658 |
+
|
| 659 |
+
def test_infer_freq_tz_transition(self):
|
| 660 |
+
# Tests for #8772
|
| 661 |
+
date_pairs = [['2013-11-02', '2013-11-5'], # Fall DST
|
| 662 |
+
['2014-03-08', '2014-03-11'], # Spring DST
|
| 663 |
+
['2014-01-01', '2014-01-03']] # Regular Time
|
| 664 |
+
freqs = ['3H', '10T', '3601S', '3600001L', '3600000001U',
|
| 665 |
+
'3600000000001N']
|
| 666 |
+
|
| 667 |
+
for tz in [None, 'Australia/Sydney', 'Asia/Tokyo', 'Europe/Paris',
|
| 668 |
+
'US/Pacific', 'US/Eastern']:
|
| 669 |
+
for date_pair in date_pairs:
|
| 670 |
+
for freq in freqs:
|
| 671 |
+
idx = date_range(date_pair[0], date_pair[
|
| 672 |
+
1], freq=freq, tz=tz)
|
| 673 |
+
assert idx.inferred_freq == freq
|
| 674 |
+
|
| 675 |
+
index = date_range("2013-11-03", periods=5,
|
| 676 |
+
freq="3H").tz_localize("America/Chicago")
|
| 677 |
+
assert index.inferred_freq is None
|
| 678 |
+
|
| 679 |
+
def test_infer_freq_businesshour(self):
|
| 680 |
+
# GH 7905
|
| 681 |
+
idx = DatetimeIndex(
|
| 682 |
+
['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
|
| 683 |
+
'2014-07-01 12:00', '2014-07-01 13:00', '2014-07-01 14:00'])
|
| 684 |
+
# hourly freq in a day must result in 'H'
|
| 685 |
+
assert idx.inferred_freq == 'H'
|
| 686 |
+
|
| 687 |
+
idx = DatetimeIndex(
|
| 688 |
+
['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
|
| 689 |
+
'2014-07-01 12:00', '2014-07-01 13:00', '2014-07-01 14:00',
|
| 690 |
+
'2014-07-01 15:00', '2014-07-01 16:00', '2014-07-02 09:00',
|
| 691 |
+
'2014-07-02 10:00', '2014-07-02 11:00'])
|
| 692 |
+
assert idx.inferred_freq == 'BH'
|
| 693 |
+
|
| 694 |
+
idx = DatetimeIndex(
|
| 695 |
+
['2014-07-04 09:00', '2014-07-04 10:00', '2014-07-04 11:00',
|
| 696 |
+
'2014-07-04 12:00', '2014-07-04 13:00', '2014-07-04 14:00',
|
| 697 |
+
'2014-07-04 15:00', '2014-07-04 16:00', '2014-07-07 09:00',
|
| 698 |
+
'2014-07-07 10:00', '2014-07-07 11:00'])
|
| 699 |
+
assert idx.inferred_freq == 'BH'
|
| 700 |
+
|
| 701 |
+
idx = DatetimeIndex(
|
| 702 |
+
['2014-07-04 09:00', '2014-07-04 10:00', '2014-07-04 11:00',
|
| 703 |
+
'2014-07-04 12:00', '2014-07-04 13:00', '2014-07-04 14:00',
|
| 704 |
+
'2014-07-04 15:00', '2014-07-04 16:00', '2014-07-07 09:00',
|
| 705 |
+
'2014-07-07 10:00', '2014-07-07 11:00', '2014-07-07 12:00',
|
| 706 |
+
'2014-07-07 13:00', '2014-07-07 14:00', '2014-07-07 15:00',
|
| 707 |
+
'2014-07-07 16:00', '2014-07-08 09:00', '2014-07-08 10:00',
|
| 708 |
+
'2014-07-08 11:00', '2014-07-08 12:00', '2014-07-08 13:00',
|
| 709 |
+
'2014-07-08 14:00', '2014-07-08 15:00', '2014-07-08 16:00'])
|
| 710 |
+
assert idx.inferred_freq == 'BH'
|
| 711 |
+
|
| 712 |
+
def test_not_monotonic(self):
|
| 713 |
+
rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
|
| 714 |
+
rng = rng[::-1]
|
| 715 |
+
assert rng.inferred_freq == '-1A-JAN'
|
| 716 |
+
|
| 717 |
+
def test_non_datetimeindex2(self):
|
| 718 |
+
rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
|
| 719 |
+
|
| 720 |
+
vals = rng.to_pydatetime()
|
| 721 |
+
|
| 722 |
+
result = frequencies.infer_freq(vals)
|
| 723 |
+
assert result == rng.inferred_freq
|
| 724 |
+
|
| 725 |
+
def test_invalid_index_types(self):
|
| 726 |
+
|
| 727 |
+
# test all index types
|
| 728 |
+
for i in [tm.makeIntIndex(10), tm.makeFloatIndex(10),
|
| 729 |
+
tm.makePeriodIndex(10)]:
|
| 730 |
+
pytest.raises(TypeError, lambda: frequencies.infer_freq(i))
|
| 731 |
+
|
| 732 |
+
# GH 10822
|
| 733 |
+
# odd error message on conversions to datetime for unicode
|
| 734 |
+
if not is_platform_windows():
|
| 735 |
+
for i in [tm.makeStringIndex(10), tm.makeUnicodeIndex(10)]:
|
| 736 |
+
pytest.raises(ValueError, lambda: frequencies.infer_freq(i))
|
| 737 |
+
|
| 738 |
+
def test_string_datetimelike_compat(self):
|
| 739 |
+
|
| 740 |
+
# GH 6463
|
| 741 |
+
expected = frequencies.infer_freq(['2004-01', '2004-02', '2004-03',
|
| 742 |
+
'2004-04'])
|
| 743 |
+
result = frequencies.infer_freq(Index(['2004-01', '2004-02', '2004-03',
|
| 744 |
+
'2004-04']))
|
| 745 |
+
assert result == expected
|
| 746 |
+
|
| 747 |
+
def test_series(self):
|
| 748 |
+
|
| 749 |
+
# GH6407
|
| 750 |
+
# inferring series
|
| 751 |
+
|
| 752 |
+
# invalid type of Series
|
| 753 |
+
for s in [Series(np.arange(10)), Series(np.arange(10.))]:
|
| 754 |
+
pytest.raises(TypeError, lambda: frequencies.infer_freq(s))
|
| 755 |
+
|
| 756 |
+
# a non-convertible string
|
| 757 |
+
pytest.raises(ValueError, lambda: frequencies.infer_freq(
|
| 758 |
+
Series(['foo', 'bar'])))
|
| 759 |
+
|
| 760 |
+
# cannot infer on PeriodIndex
|
| 761 |
+
for freq in [None, 'L']:
|
| 762 |
+
s = Series(period_range('2013', periods=10, freq=freq))
|
| 763 |
+
pytest.raises(TypeError, lambda: frequencies.infer_freq(s))
|
| 764 |
+
|
| 765 |
+
# DateTimeIndex
|
| 766 |
+
for freq in ['M', 'L', 'S']:
|
| 767 |
+
s = Series(date_range('20130101', periods=10, freq=freq))
|
| 768 |
+
inferred = frequencies.infer_freq(s)
|
| 769 |
+
assert inferred == freq
|
| 770 |
+
|
| 771 |
+
s = Series(date_range('20130101', '20130110'))
|
| 772 |
+
inferred = frequencies.infer_freq(s)
|
| 773 |
+
assert inferred == 'D'
|
| 774 |
+
|
| 775 |
+
def test_legacy_offset_warnings(self):
|
| 776 |
+
freqs = ['WEEKDAY', 'EOM', 'W@MON', 'W@TUE', 'W@WED', 'W@THU',
|
| 777 |
+
'W@FRI', 'W@SAT', 'W@SUN', 'Q@JAN', 'Q@FEB', 'Q@MAR',
|
| 778 |
+
'A@JAN', 'A@FEB', 'A@MAR', 'A@APR', 'A@MAY', 'A@JUN',
|
| 779 |
+
'A@JUL', 'A@AUG', 'A@SEP', 'A@OCT', 'A@NOV', 'A@DEC',
|
| 780 |
+
'Y@JAN', 'WOM@1MON', 'WOM@2MON', 'WOM@3MON',
|
| 781 |
+
'WOM@4MON', 'WOM@1TUE', 'WOM@2TUE', 'WOM@3TUE',
|
| 782 |
+
'WOM@4TUE', 'WOM@1WED', 'WOM@2WED', 'WOM@3WED',
|
| 783 |
+
'WOM@4WED', 'WOM@1THU', 'WOM@2THU', 'WOM@3THU',
|
| 784 |
+
'WOM@4THU', 'WOM@1FRI', 'WOM@2FRI', 'WOM@3FRI',
|
| 785 |
+
'WOM@4FRI']
|
| 786 |
+
|
| 787 |
+
msg = INVALID_FREQ_ERR_MSG
|
| 788 |
+
for freq in freqs:
|
| 789 |
+
with pytest.raises(ValueError, match=msg):
|
| 790 |
+
frequencies.get_offset(freq)
|
| 791 |
+
|
| 792 |
+
with pytest.raises(ValueError, match=msg):
|
| 793 |
+
date_range('2011-01-01', periods=5, freq=freq)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tseries/test_holiday.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
from pytz import utc
|
| 5 |
+
|
| 6 |
+
from pandas import DatetimeIndex, compat
|
| 7 |
+
import pandas.util.testing as tm
|
| 8 |
+
|
| 9 |
+
from pandas.tseries.holiday import (
|
| 10 |
+
MO, SA, AbstractHolidayCalendar, DateOffset, EasterMonday, GoodFriday,
|
| 11 |
+
Holiday, HolidayCalendarFactory, Timestamp, USColumbusDay,
|
| 12 |
+
USFederalHolidayCalendar, USLaborDay, USMartinLutherKingJr, USMemorialDay,
|
| 13 |
+
USPresidentsDay, USThanksgivingDay, after_nearest_workday,
|
| 14 |
+
before_nearest_workday, get_calendar, nearest_workday, next_monday,
|
| 15 |
+
next_monday_or_tuesday, next_workday, previous_friday, previous_workday,
|
| 16 |
+
sunday_to_monday, weekend_to_monday)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestCalendar(object):
|
| 20 |
+
|
| 21 |
+
def setup_method(self, method):
|
| 22 |
+
self.holiday_list = [
|
| 23 |
+
datetime(2012, 1, 2),
|
| 24 |
+
datetime(2012, 1, 16),
|
| 25 |
+
datetime(2012, 2, 20),
|
| 26 |
+
datetime(2012, 5, 28),
|
| 27 |
+
datetime(2012, 7, 4),
|
| 28 |
+
datetime(2012, 9, 3),
|
| 29 |
+
datetime(2012, 10, 8),
|
| 30 |
+
datetime(2012, 11, 12),
|
| 31 |
+
datetime(2012, 11, 22),
|
| 32 |
+
datetime(2012, 12, 25)]
|
| 33 |
+
|
| 34 |
+
self.start_date = datetime(2012, 1, 1)
|
| 35 |
+
self.end_date = datetime(2012, 12, 31)
|
| 36 |
+
|
| 37 |
+
def test_calendar(self):
|
| 38 |
+
|
| 39 |
+
calendar = USFederalHolidayCalendar()
|
| 40 |
+
holidays = calendar.holidays(self.start_date, self.end_date)
|
| 41 |
+
|
| 42 |
+
holidays_1 = calendar.holidays(
|
| 43 |
+
self.start_date.strftime('%Y-%m-%d'),
|
| 44 |
+
self.end_date.strftime('%Y-%m-%d'))
|
| 45 |
+
holidays_2 = calendar.holidays(
|
| 46 |
+
Timestamp(self.start_date),
|
| 47 |
+
Timestamp(self.end_date))
|
| 48 |
+
|
| 49 |
+
assert list(holidays.to_pydatetime()) == self.holiday_list
|
| 50 |
+
assert list(holidays_1.to_pydatetime()) == self.holiday_list
|
| 51 |
+
assert list(holidays_2.to_pydatetime()) == self.holiday_list
|
| 52 |
+
|
| 53 |
+
def test_calendar_caching(self):
|
| 54 |
+
# Test for issue #9552
|
| 55 |
+
|
| 56 |
+
class TestCalendar(AbstractHolidayCalendar):
|
| 57 |
+
|
| 58 |
+
def __init__(self, name=None, rules=None):
|
| 59 |
+
super(TestCalendar, self).__init__(name=name, rules=rules)
|
| 60 |
+
|
| 61 |
+
jan1 = TestCalendar(rules=[Holiday('jan1', year=2015, month=1, day=1)])
|
| 62 |
+
jan2 = TestCalendar(rules=[Holiday('jan2', year=2015, month=1, day=2)])
|
| 63 |
+
|
| 64 |
+
tm.assert_index_equal(jan1.holidays(), DatetimeIndex(['01-Jan-2015']))
|
| 65 |
+
tm.assert_index_equal(jan2.holidays(), DatetimeIndex(['02-Jan-2015']))
|
| 66 |
+
|
| 67 |
+
def test_calendar_observance_dates(self):
|
| 68 |
+
# Test for issue 11477
|
| 69 |
+
USFedCal = get_calendar('USFederalHolidayCalendar')
|
| 70 |
+
holidays0 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
|
| 71 |
+
2015, 7, 3)) # <-- same start and end dates
|
| 72 |
+
holidays1 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
|
| 73 |
+
2015, 7, 6)) # <-- different start and end dates
|
| 74 |
+
holidays2 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
|
| 75 |
+
2015, 7, 3)) # <-- same start and end dates
|
| 76 |
+
|
| 77 |
+
tm.assert_index_equal(holidays0, holidays1)
|
| 78 |
+
tm.assert_index_equal(holidays0, holidays2)
|
| 79 |
+
|
| 80 |
+
def test_rule_from_name(self):
|
| 81 |
+
USFedCal = get_calendar('USFederalHolidayCalendar')
|
| 82 |
+
assert USFedCal.rule_from_name('Thanksgiving') == USThanksgivingDay
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestHoliday(object):
|
| 86 |
+
|
| 87 |
+
def setup_method(self, method):
|
| 88 |
+
self.start_date = datetime(2011, 1, 1)
|
| 89 |
+
self.end_date = datetime(2020, 12, 31)
|
| 90 |
+
|
| 91 |
+
def check_results(self, holiday, start, end, expected):
|
| 92 |
+
assert list(holiday.dates(start, end)) == expected
|
| 93 |
+
|
| 94 |
+
# Verify that timezone info is preserved.
|
| 95 |
+
assert (list(holiday.dates(utc.localize(Timestamp(start)),
|
| 96 |
+
utc.localize(Timestamp(end)))) ==
|
| 97 |
+
[utc.localize(dt) for dt in expected])
|
| 98 |
+
|
| 99 |
+
def test_usmemorialday(self):
|
| 100 |
+
self.check_results(holiday=USMemorialDay,
|
| 101 |
+
start=self.start_date,
|
| 102 |
+
end=self.end_date,
|
| 103 |
+
expected=[
|
| 104 |
+
datetime(2011, 5, 30),
|
| 105 |
+
datetime(2012, 5, 28),
|
| 106 |
+
datetime(2013, 5, 27),
|
| 107 |
+
datetime(2014, 5, 26),
|
| 108 |
+
datetime(2015, 5, 25),
|
| 109 |
+
datetime(2016, 5, 30),
|
| 110 |
+
datetime(2017, 5, 29),
|
| 111 |
+
datetime(2018, 5, 28),
|
| 112 |
+
datetime(2019, 5, 27),
|
| 113 |
+
datetime(2020, 5, 25),
|
| 114 |
+
], )
|
| 115 |
+
|
| 116 |
+
def test_non_observed_holiday(self):
|
| 117 |
+
|
| 118 |
+
self.check_results(
|
| 119 |
+
Holiday('July 4th Eve', month=7, day=3),
|
| 120 |
+
start="2001-01-01",
|
| 121 |
+
end="2003-03-03",
|
| 122 |
+
expected=[
|
| 123 |
+
Timestamp('2001-07-03 00:00:00'),
|
| 124 |
+
Timestamp('2002-07-03 00:00:00')
|
| 125 |
+
]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.check_results(
|
| 129 |
+
Holiday('July 4th Eve', month=7, day=3, days_of_week=(0, 1, 2, 3)),
|
| 130 |
+
start="2001-01-01",
|
| 131 |
+
end="2008-03-03",
|
| 132 |
+
expected=[
|
| 133 |
+
Timestamp('2001-07-03 00:00:00'),
|
| 134 |
+
Timestamp('2002-07-03 00:00:00'),
|
| 135 |
+
Timestamp('2003-07-03 00:00:00'),
|
| 136 |
+
Timestamp('2006-07-03 00:00:00'),
|
| 137 |
+
Timestamp('2007-07-03 00:00:00'),
|
| 138 |
+
]
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
def test_easter(self):
|
| 142 |
+
|
| 143 |
+
self.check_results(EasterMonday,
|
| 144 |
+
start=self.start_date,
|
| 145 |
+
end=self.end_date,
|
| 146 |
+
expected=[
|
| 147 |
+
Timestamp('2011-04-25 00:00:00'),
|
| 148 |
+
Timestamp('2012-04-09 00:00:00'),
|
| 149 |
+
Timestamp('2013-04-01 00:00:00'),
|
| 150 |
+
Timestamp('2014-04-21 00:00:00'),
|
| 151 |
+
Timestamp('2015-04-06 00:00:00'),
|
| 152 |
+
Timestamp('2016-03-28 00:00:00'),
|
| 153 |
+
Timestamp('2017-04-17 00:00:00'),
|
| 154 |
+
Timestamp('2018-04-02 00:00:00'),
|
| 155 |
+
Timestamp('2019-04-22 00:00:00'),
|
| 156 |
+
Timestamp('2020-04-13 00:00:00'),
|
| 157 |
+
], )
|
| 158 |
+
self.check_results(GoodFriday,
|
| 159 |
+
start=self.start_date,
|
| 160 |
+
end=self.end_date,
|
| 161 |
+
expected=[
|
| 162 |
+
Timestamp('2011-04-22 00:00:00'),
|
| 163 |
+
Timestamp('2012-04-06 00:00:00'),
|
| 164 |
+
Timestamp('2013-03-29 00:00:00'),
|
| 165 |
+
Timestamp('2014-04-18 00:00:00'),
|
| 166 |
+
Timestamp('2015-04-03 00:00:00'),
|
| 167 |
+
Timestamp('2016-03-25 00:00:00'),
|
| 168 |
+
Timestamp('2017-04-14 00:00:00'),
|
| 169 |
+
Timestamp('2018-03-30 00:00:00'),
|
| 170 |
+
Timestamp('2019-04-19 00:00:00'),
|
| 171 |
+
Timestamp('2020-04-10 00:00:00'),
|
| 172 |
+
], )
|
| 173 |
+
|
| 174 |
+
def test_usthanksgivingday(self):
|
| 175 |
+
|
| 176 |
+
self.check_results(USThanksgivingDay,
|
| 177 |
+
start=self.start_date,
|
| 178 |
+
end=self.end_date,
|
| 179 |
+
expected=[
|
| 180 |
+
datetime(2011, 11, 24),
|
| 181 |
+
datetime(2012, 11, 22),
|
| 182 |
+
datetime(2013, 11, 28),
|
| 183 |
+
datetime(2014, 11, 27),
|
| 184 |
+
datetime(2015, 11, 26),
|
| 185 |
+
datetime(2016, 11, 24),
|
| 186 |
+
datetime(2017, 11, 23),
|
| 187 |
+
datetime(2018, 11, 22),
|
| 188 |
+
datetime(2019, 11, 28),
|
| 189 |
+
datetime(2020, 11, 26),
|
| 190 |
+
], )
|
| 191 |
+
|
| 192 |
+
def test_holidays_within_dates(self):
|
| 193 |
+
# Fix holiday behavior found in #11477
|
| 194 |
+
# where holiday.dates returned dates outside start/end date
|
| 195 |
+
# or observed rules could not be applied as the holiday
|
| 196 |
+
# was not in the original date range (e.g., 7/4/2015 -> 7/3/2015)
|
| 197 |
+
start_date = datetime(2015, 7, 1)
|
| 198 |
+
end_date = datetime(2015, 7, 1)
|
| 199 |
+
|
| 200 |
+
calendar = get_calendar('USFederalHolidayCalendar')
|
| 201 |
+
new_years = calendar.rule_from_name('New Years Day')
|
| 202 |
+
july_4th = calendar.rule_from_name('July 4th')
|
| 203 |
+
veterans_day = calendar.rule_from_name('Veterans Day')
|
| 204 |
+
christmas = calendar.rule_from_name('Christmas')
|
| 205 |
+
|
| 206 |
+
# Holiday: (start/end date, holiday)
|
| 207 |
+
holidays = {USMemorialDay: ("2015-05-25", "2015-05-25"),
|
| 208 |
+
USLaborDay: ("2015-09-07", "2015-09-07"),
|
| 209 |
+
USColumbusDay: ("2015-10-12", "2015-10-12"),
|
| 210 |
+
USThanksgivingDay: ("2015-11-26", "2015-11-26"),
|
| 211 |
+
USMartinLutherKingJr: ("2015-01-19", "2015-01-19"),
|
| 212 |
+
USPresidentsDay: ("2015-02-16", "2015-02-16"),
|
| 213 |
+
GoodFriday: ("2015-04-03", "2015-04-03"),
|
| 214 |
+
EasterMonday: [("2015-04-06", "2015-04-06"),
|
| 215 |
+
("2015-04-05", [])],
|
| 216 |
+
new_years: [("2015-01-01", "2015-01-01"),
|
| 217 |
+
("2011-01-01", []),
|
| 218 |
+
("2010-12-31", "2010-12-31")],
|
| 219 |
+
july_4th: [("2015-07-03", "2015-07-03"),
|
| 220 |
+
("2015-07-04", [])],
|
| 221 |
+
veterans_day: [("2012-11-11", []),
|
| 222 |
+
("2012-11-12", "2012-11-12")],
|
| 223 |
+
christmas: [("2011-12-25", []),
|
| 224 |
+
("2011-12-26", "2011-12-26")]}
|
| 225 |
+
|
| 226 |
+
for rule, dates in compat.iteritems(holidays):
|
| 227 |
+
empty_dates = rule.dates(start_date, end_date)
|
| 228 |
+
assert empty_dates.tolist() == []
|
| 229 |
+
|
| 230 |
+
if isinstance(dates, tuple):
|
| 231 |
+
dates = [dates]
|
| 232 |
+
|
| 233 |
+
for start, expected in dates:
|
| 234 |
+
if len(expected):
|
| 235 |
+
expected = [Timestamp(expected)]
|
| 236 |
+
self.check_results(rule, start, start, expected)
|
| 237 |
+
|
| 238 |
+
def test_argument_types(self):
|
| 239 |
+
holidays = USThanksgivingDay.dates(self.start_date, self.end_date)
|
| 240 |
+
|
| 241 |
+
holidays_1 = USThanksgivingDay.dates(
|
| 242 |
+
self.start_date.strftime('%Y-%m-%d'),
|
| 243 |
+
self.end_date.strftime('%Y-%m-%d'))
|
| 244 |
+
|
| 245 |
+
holidays_2 = USThanksgivingDay.dates(
|
| 246 |
+
Timestamp(self.start_date),
|
| 247 |
+
Timestamp(self.end_date))
|
| 248 |
+
|
| 249 |
+
tm.assert_index_equal(holidays, holidays_1)
|
| 250 |
+
tm.assert_index_equal(holidays, holidays_2)
|
| 251 |
+
|
| 252 |
+
def test_special_holidays(self):
|
| 253 |
+
base_date = [datetime(2012, 5, 28)]
|
| 254 |
+
holiday_1 = Holiday('One-Time', year=2012, month=5, day=28)
|
| 255 |
+
holiday_2 = Holiday('Range', month=5, day=28,
|
| 256 |
+
start_date=datetime(2012, 1, 1),
|
| 257 |
+
end_date=datetime(2012, 12, 31),
|
| 258 |
+
offset=DateOffset(weekday=MO(1)))
|
| 259 |
+
|
| 260 |
+
assert base_date == holiday_1.dates(self.start_date, self.end_date)
|
| 261 |
+
assert base_date == holiday_2.dates(self.start_date, self.end_date)
|
| 262 |
+
|
| 263 |
+
def test_get_calendar(self):
|
| 264 |
+
class TestCalendar(AbstractHolidayCalendar):
|
| 265 |
+
rules = []
|
| 266 |
+
|
| 267 |
+
calendar = get_calendar('TestCalendar')
|
| 268 |
+
assert TestCalendar == calendar.__class__
|
| 269 |
+
|
| 270 |
+
def test_factory(self):
|
| 271 |
+
class_1 = HolidayCalendarFactory('MemorialDay',
|
| 272 |
+
AbstractHolidayCalendar,
|
| 273 |
+
USMemorialDay)
|
| 274 |
+
class_2 = HolidayCalendarFactory('Thansksgiving',
|
| 275 |
+
AbstractHolidayCalendar,
|
| 276 |
+
USThanksgivingDay)
|
| 277 |
+
class_3 = HolidayCalendarFactory('Combined', class_1, class_2)
|
| 278 |
+
|
| 279 |
+
assert len(class_1.rules) == 1
|
| 280 |
+
assert len(class_2.rules) == 1
|
| 281 |
+
assert len(class_3.rules) == 2
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class TestObservanceRules(object):
|
| 285 |
+
|
| 286 |
+
def setup_method(self, method):
|
| 287 |
+
self.we = datetime(2014, 4, 9)
|
| 288 |
+
self.th = datetime(2014, 4, 10)
|
| 289 |
+
self.fr = datetime(2014, 4, 11)
|
| 290 |
+
self.sa = datetime(2014, 4, 12)
|
| 291 |
+
self.su = datetime(2014, 4, 13)
|
| 292 |
+
self.mo = datetime(2014, 4, 14)
|
| 293 |
+
self.tu = datetime(2014, 4, 15)
|
| 294 |
+
|
| 295 |
+
def test_next_monday(self):
|
| 296 |
+
assert next_monday(self.sa) == self.mo
|
| 297 |
+
assert next_monday(self.su) == self.mo
|
| 298 |
+
|
| 299 |
+
def test_next_monday_or_tuesday(self):
|
| 300 |
+
assert next_monday_or_tuesday(self.sa) == self.mo
|
| 301 |
+
assert next_monday_or_tuesday(self.su) == self.tu
|
| 302 |
+
assert next_monday_or_tuesday(self.mo) == self.tu
|
| 303 |
+
|
| 304 |
+
def test_previous_friday(self):
|
| 305 |
+
assert previous_friday(self.sa) == self.fr
|
| 306 |
+
assert previous_friday(self.su) == self.fr
|
| 307 |
+
|
| 308 |
+
def test_sunday_to_monday(self):
|
| 309 |
+
assert sunday_to_monday(self.su) == self.mo
|
| 310 |
+
|
| 311 |
+
def test_nearest_workday(self):
|
| 312 |
+
assert nearest_workday(self.sa) == self.fr
|
| 313 |
+
assert nearest_workday(self.su) == self.mo
|
| 314 |
+
assert nearest_workday(self.mo) == self.mo
|
| 315 |
+
|
| 316 |
+
def test_weekend_to_monday(self):
|
| 317 |
+
assert weekend_to_monday(self.sa) == self.mo
|
| 318 |
+
assert weekend_to_monday(self.su) == self.mo
|
| 319 |
+
assert weekend_to_monday(self.mo) == self.mo
|
| 320 |
+
|
| 321 |
+
def test_next_workday(self):
|
| 322 |
+
assert next_workday(self.sa) == self.mo
|
| 323 |
+
assert next_workday(self.su) == self.mo
|
| 324 |
+
assert next_workday(self.mo) == self.tu
|
| 325 |
+
|
| 326 |
+
def test_previous_workday(self):
|
| 327 |
+
assert previous_workday(self.sa) == self.fr
|
| 328 |
+
assert previous_workday(self.su) == self.fr
|
| 329 |
+
assert previous_workday(self.tu) == self.mo
|
| 330 |
+
|
| 331 |
+
def test_before_nearest_workday(self):
|
| 332 |
+
assert before_nearest_workday(self.sa) == self.th
|
| 333 |
+
assert before_nearest_workday(self.su) == self.fr
|
| 334 |
+
assert before_nearest_workday(self.tu) == self.mo
|
| 335 |
+
|
| 336 |
+
def test_after_nearest_workday(self):
|
| 337 |
+
assert after_nearest_workday(self.sa) == self.mo
|
| 338 |
+
assert after_nearest_workday(self.su) == self.tu
|
| 339 |
+
assert after_nearest_workday(self.fr) == self.mo
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class TestFederalHolidayCalendar(object):
|
| 343 |
+
|
| 344 |
+
def test_no_mlk_before_1986(self):
|
| 345 |
+
# see gh-10278
|
| 346 |
+
class MLKCalendar(AbstractHolidayCalendar):
|
| 347 |
+
rules = [USMartinLutherKingJr]
|
| 348 |
+
|
| 349 |
+
holidays = MLKCalendar().holidays(start='1984',
|
| 350 |
+
end='1988').to_pydatetime().tolist()
|
| 351 |
+
|
| 352 |
+
# Testing to make sure holiday is not incorrectly observed before 1986
|
| 353 |
+
assert holidays == [datetime(1986, 1, 20, 0, 0),
|
| 354 |
+
datetime(1987, 1, 19, 0, 0)]
|
| 355 |
+
|
| 356 |
+
def test_memorial_day(self):
|
| 357 |
+
class MemorialDay(AbstractHolidayCalendar):
|
| 358 |
+
rules = [USMemorialDay]
|
| 359 |
+
|
| 360 |
+
holidays = MemorialDay().holidays(start='1971',
|
| 361 |
+
end='1980').to_pydatetime().tolist()
|
| 362 |
+
|
| 363 |
+
# Fixes 5/31 error and checked manually against Wikipedia
|
| 364 |
+
assert holidays == [datetime(1971, 5, 31, 0, 0),
|
| 365 |
+
datetime(1972, 5, 29, 0, 0),
|
| 366 |
+
datetime(1973, 5, 28, 0, 0),
|
| 367 |
+
datetime(1974, 5, 27, 0, 0),
|
| 368 |
+
datetime(1975, 5, 26, 0, 0),
|
| 369 |
+
datetime(1976, 5, 31, 0, 0),
|
| 370 |
+
datetime(1977, 5, 30, 0, 0),
|
| 371 |
+
datetime(1978, 5, 29, 0, 0),
|
| 372 |
+
datetime(1979, 5, 28, 0, 0)]
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class TestHolidayConflictingArguments(object):
|
| 376 |
+
|
| 377 |
+
def test_both_offset_observance_raises(self):
|
| 378 |
+
# see gh-10217
|
| 379 |
+
with pytest.raises(NotImplementedError):
|
| 380 |
+
Holiday("Cyber Monday", month=11, day=1,
|
| 381 |
+
offset=[DateOffset(weekday=SA(4))],
|
| 382 |
+
observance=next_monday)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_api.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Tests that the tslibs API is locked down"""
|
| 3 |
+
|
| 4 |
+
from pandas._libs import tslibs
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_namespace():
|
| 8 |
+
|
| 9 |
+
submodules = ['ccalendar',
|
| 10 |
+
'conversion',
|
| 11 |
+
'fields',
|
| 12 |
+
'frequencies',
|
| 13 |
+
'nattype',
|
| 14 |
+
'np_datetime',
|
| 15 |
+
'offsets',
|
| 16 |
+
'parsing',
|
| 17 |
+
'period',
|
| 18 |
+
'resolution',
|
| 19 |
+
'strptime',
|
| 20 |
+
'timedeltas',
|
| 21 |
+
'timestamps',
|
| 22 |
+
'timezones']
|
| 23 |
+
|
| 24 |
+
api = ['NaT',
|
| 25 |
+
'iNaT',
|
| 26 |
+
'is_null_datetimelike',
|
| 27 |
+
'OutOfBoundsDatetime',
|
| 28 |
+
'Period',
|
| 29 |
+
'IncompatibleFrequency',
|
| 30 |
+
'Timedelta',
|
| 31 |
+
'Timestamp',
|
| 32 |
+
'delta_to_nanoseconds',
|
| 33 |
+
'ints_to_pytimedelta',
|
| 34 |
+
'localize_pydatetime',
|
| 35 |
+
'normalize_date',
|
| 36 |
+
'tz_convert_single']
|
| 37 |
+
|
| 38 |
+
expected = set(submodules + api)
|
| 39 |
+
names = [x for x in dir(tslibs) if not x.startswith('__')]
|
| 40 |
+
assert set(names) == expected
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_array_to_datetime.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from datetime import date, datetime
|
| 3 |
+
|
| 4 |
+
from dateutil.tz.tz import tzoffset
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
import pytz
|
| 8 |
+
|
| 9 |
+
from pandas._libs import iNaT, tslib
|
| 10 |
+
from pandas.compat.numpy import np_array_datetime64_compat
|
| 11 |
+
|
| 12 |
+
import pandas.util.testing as tm
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize("data,expected", [
|
| 16 |
+
(["01-01-2013", "01-02-2013"],
|
| 17 |
+
["2013-01-01T00:00:00.000000000-0000",
|
| 18 |
+
"2013-01-02T00:00:00.000000000-0000"]),
|
| 19 |
+
(["Mon Sep 16 2013", "Tue Sep 17 2013"],
|
| 20 |
+
["2013-09-16T00:00:00.000000000-0000",
|
| 21 |
+
"2013-09-17T00:00:00.000000000-0000"])
|
| 22 |
+
])
|
| 23 |
+
def test_parsing_valid_dates(data, expected):
|
| 24 |
+
arr = np.array(data, dtype=object)
|
| 25 |
+
result, _ = tslib.array_to_datetime(arr)
|
| 26 |
+
|
| 27 |
+
expected = np_array_datetime64_compat(expected, dtype="M8[ns]")
|
| 28 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@pytest.mark.parametrize("dt_string, expected_tz", [
|
| 32 |
+
["01-01-2013 08:00:00+08:00", 480],
|
| 33 |
+
["2013-01-01T08:00:00.000000000+0800", 480],
|
| 34 |
+
["2012-12-31T16:00:00.000000000-0800", -480],
|
| 35 |
+
["12-31-2012 23:00:00-01:00", -60]
|
| 36 |
+
])
|
| 37 |
+
def test_parsing_timezone_offsets(dt_string, expected_tz):
|
| 38 |
+
# All of these datetime strings with offsets are equivalent
|
| 39 |
+
# to the same datetime after the timezone offset is added.
|
| 40 |
+
arr = np.array(["01-01-2013 00:00:00"], dtype=object)
|
| 41 |
+
expected, _ = tslib.array_to_datetime(arr)
|
| 42 |
+
|
| 43 |
+
arr = np.array([dt_string], dtype=object)
|
| 44 |
+
result, result_tz = tslib.array_to_datetime(arr)
|
| 45 |
+
|
| 46 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 47 |
+
assert result_tz is pytz.FixedOffset(expected_tz)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_parsing_non_iso_timezone_offset():
|
| 51 |
+
dt_string = "01-01-2013T00:00:00.000000000+0000"
|
| 52 |
+
arr = np.array([dt_string], dtype=object)
|
| 53 |
+
|
| 54 |
+
result, result_tz = tslib.array_to_datetime(arr)
|
| 55 |
+
expected = np.array([np.datetime64("2013-01-01 00:00:00.000000000")])
|
| 56 |
+
|
| 57 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 58 |
+
assert result_tz is pytz.FixedOffset(0)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_parsing_different_timezone_offsets():
|
| 62 |
+
# see gh-17697
|
| 63 |
+
data = ["2015-11-18 15:30:00+05:30", "2015-11-18 15:30:00+06:30"]
|
| 64 |
+
data = np.array(data, dtype=object)
|
| 65 |
+
|
| 66 |
+
result, result_tz = tslib.array_to_datetime(data)
|
| 67 |
+
expected = np.array([datetime(2015, 11, 18, 15, 30,
|
| 68 |
+
tzinfo=tzoffset(None, 19800)),
|
| 69 |
+
datetime(2015, 11, 18, 15, 30,
|
| 70 |
+
tzinfo=tzoffset(None, 23400))],
|
| 71 |
+
dtype=object)
|
| 72 |
+
|
| 73 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 74 |
+
assert result_tz is None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@pytest.mark.parametrize("data", [
|
| 78 |
+
["-352.737091", "183.575577"],
|
| 79 |
+
["1", "2", "3", "4", "5"]
|
| 80 |
+
])
|
| 81 |
+
def test_number_looking_strings_not_into_datetime(data):
|
| 82 |
+
# see gh-4601
|
| 83 |
+
#
|
| 84 |
+
# These strings don't look like datetimes, so
|
| 85 |
+
# they shouldn't be attempted to be converted.
|
| 86 |
+
arr = np.array(data, dtype=object)
|
| 87 |
+
result, _ = tslib.array_to_datetime(arr, errors="ignore")
|
| 88 |
+
|
| 89 |
+
tm.assert_numpy_array_equal(result, arr)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize("invalid_date", [
|
| 93 |
+
date(1000, 1, 1),
|
| 94 |
+
datetime(1000, 1, 1),
|
| 95 |
+
"1000-01-01",
|
| 96 |
+
"Jan 1, 1000",
|
| 97 |
+
np.datetime64("1000-01-01")])
|
| 98 |
+
@pytest.mark.parametrize("errors", ["coerce", "raise"])
|
| 99 |
+
def test_coerce_outside_ns_bounds(invalid_date, errors):
|
| 100 |
+
arr = np.array([invalid_date], dtype="object")
|
| 101 |
+
kwargs = dict(values=arr, errors=errors)
|
| 102 |
+
|
| 103 |
+
if errors == "raise":
|
| 104 |
+
msg = "Out of bounds nanosecond timestamp"
|
| 105 |
+
|
| 106 |
+
with pytest.raises(ValueError, match=msg):
|
| 107 |
+
tslib.array_to_datetime(**kwargs)
|
| 108 |
+
else: # coerce.
|
| 109 |
+
result, _ = tslib.array_to_datetime(**kwargs)
|
| 110 |
+
expected = np.array([iNaT], dtype="M8[ns]")
|
| 111 |
+
|
| 112 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_coerce_outside_ns_bounds_one_valid():
|
| 116 |
+
arr = np.array(["1/1/1000", "1/1/2000"], dtype=object)
|
| 117 |
+
result, _ = tslib.array_to_datetime(arr, errors="coerce")
|
| 118 |
+
|
| 119 |
+
expected = [iNaT, "2000-01-01T00:00:00.000000000-0000"]
|
| 120 |
+
expected = np_array_datetime64_compat(expected, dtype="M8[ns]")
|
| 121 |
+
|
| 122 |
+
tm.assert_numpy_array_equal(result, expected)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize("errors", ["ignore", "coerce"])
|
| 126 |
+
def test_coerce_of_invalid_datetimes(errors):
|
| 127 |
+
arr = np.array(["01-01-2013", "not_a_date", "1"], dtype=object)
|
| 128 |
+
kwargs = dict(values=arr, errors=errors)
|
| 129 |
+
|
| 130 |
+
if errors == "ignore":
|
| 131 |
+
# Without coercing, the presence of any invalid
|
| 132 |
+
# dates prevents any values from being converted.
|
| 133 |
+
result, _ = tslib.array_to_datetime(**kwargs)
|
| 134 |
+
tm.assert_numpy_array_equal(result, arr)
|
| 135 |
+
else: # coerce.
|
| 136 |
+
# With coercing, the invalid dates becomes iNaT
|
| 137 |
+
result, _ = tslib.array_to_datetime(arr, errors="coerce")
|
| 138 |
+
expected = ["2013-01-01T00:00:00.000000000-0000",
|
| 139 |
+
iNaT,
|
| 140 |
+
iNaT]
|
| 141 |
+
|
| 142 |
+
tm.assert_numpy_array_equal(
|
| 143 |
+
result,
|
| 144 |
+
np_array_datetime64_compat(expected, dtype="M8[ns]"))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_to_datetime_barely_out_of_bounds():
|
| 148 |
+
# see gh-19382, gh-19529
|
| 149 |
+
#
|
| 150 |
+
# Close enough to bounds that dropping nanos
|
| 151 |
+
# would result in an in-bounds datetime.
|
| 152 |
+
arr = np.array(["2262-04-11 23:47:16.854775808"], dtype=object)
|
| 153 |
+
msg = "Out of bounds nanosecond timestamp: 2262-04-11 23:47:16"
|
| 154 |
+
|
| 155 |
+
with pytest.raises(tslib.OutOfBoundsDatetime, match=msg):
|
| 156 |
+
tslib.array_to_datetime(arr)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/pandas/tests/tslibs/test_ccalendar.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from pandas._libs.tslibs import ccalendar
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.parametrize("date_tuple,expected", [
|
| 11 |
+
((2001, 3, 1), 60),
|
| 12 |
+
((2004, 3, 1), 61),
|
| 13 |
+
((1907, 12, 31), 365), # End-of-year, non-leap year.
|
| 14 |
+
((2004, 12, 31), 366), # End-of-year, leap year.
|
| 15 |
+
])
|
| 16 |
+
def test_get_day_of_year_numeric(date_tuple, expected):
|
| 17 |
+
assert ccalendar.get_day_of_year(*date_tuple) == expected
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_get_day_of_year_dt():
|
| 21 |
+
dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
|
| 22 |
+
result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)
|
| 23 |
+
|
| 24 |
+
expected = (dt - dt.replace(month=1, day=1)).days + 1
|
| 25 |
+
assert result == expected
|