Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odf.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odswriter.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_readers.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_style.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_writers.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/conftest.py +41 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_openpyxl.py +398 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_readers.py +1674 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_writers.py +1334 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/conftest.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_c_parser_only.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_comment.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_compression.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_concatenate_chunks.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_converters.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_dialect.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_encoding.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_header.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_index_col.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_mangle_dupes.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_multi_thread.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_na_values.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_network.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_parse_dates.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_read_fwf.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_skiprows.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_textreader.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_upcast.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/__init__.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_chunksize.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_common_basic.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_data_list.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_decimal.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_file_buffer_url.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_float.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_index.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_inf.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_ints.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_iterator.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_read_errors.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_verbose.cpython-310.pyc +0 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_common_basic.py +864 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_data_list.py +87 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_decimal.py +63 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_file_buffer_url.py +423 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_index.py +299 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_ints.py +215 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_iterator.py +108 -0
- videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_read_errors.py +274 -0
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odf.cpython-310.pyc
ADDED
|
Binary file (1.77 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_odswriter.cpython-310.pyc
ADDED
|
Binary file (1.78 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_readers.cpython-310.pyc
ADDED
|
Binary file (46 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_style.cpython-310.pyc
ADDED
|
Binary file (8.58 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_writers.cpython-310.pyc
ADDED
|
Binary file (40.5 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-310.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/conftest.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import pandas._testing as tm
|
| 4 |
+
|
| 5 |
+
from pandas.io.parsers import read_csv
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def frame(float_frame):
|
| 10 |
+
"""
|
| 11 |
+
Returns the first ten items in fixture "float_frame".
|
| 12 |
+
"""
|
| 13 |
+
return float_frame[:10]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def tsframe():
|
| 18 |
+
return tm.makeTimeDataFrame()[:5]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.fixture(params=[True, False])
|
| 22 |
+
def merge_cells(request):
|
| 23 |
+
return request.param
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@pytest.fixture
|
| 27 |
+
def df_ref(datapath):
|
| 28 |
+
"""
|
| 29 |
+
Obtain the reference data from read_csv with the Python engine.
|
| 30 |
+
"""
|
| 31 |
+
filepath = datapath("io", "data", "csv", "test1.csv")
|
| 32 |
+
df_ref = read_csv(filepath, index_col=0, parse_dates=True, engine="python")
|
| 33 |
+
return df_ref
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.fixture(params=[".xls", ".xlsx", ".xlsm", ".ods", ".xlsb"])
|
| 37 |
+
def read_ext(request):
|
| 38 |
+
"""
|
| 39 |
+
Valid extensions for reading Excel files.
|
| 40 |
+
"""
|
| 41 |
+
return request.param
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_openpyxl.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from pandas import DataFrame
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
from pandas.io.excel import (
|
| 13 |
+
ExcelWriter,
|
| 14 |
+
_OpenpyxlWriter,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
openpyxl = pytest.importorskip("openpyxl")
|
| 18 |
+
|
| 19 |
+
pytestmark = pytest.mark.parametrize("ext", [".xlsx"])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_to_excel_styleconverter(ext):
|
| 23 |
+
from openpyxl import styles
|
| 24 |
+
|
| 25 |
+
hstyle = {
|
| 26 |
+
"font": {"color": "00FF0000", "bold": True},
|
| 27 |
+
"borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"},
|
| 28 |
+
"alignment": {"horizontal": "center", "vertical": "top"},
|
| 29 |
+
"fill": {"patternType": "solid", "fgColor": {"rgb": "006666FF", "tint": 0.3}},
|
| 30 |
+
"number_format": {"format_code": "0.00"},
|
| 31 |
+
"protection": {"locked": True, "hidden": False},
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
font_color = styles.Color("00FF0000")
|
| 35 |
+
font = styles.Font(bold=True, color=font_color)
|
| 36 |
+
side = styles.Side(style=styles.borders.BORDER_THIN)
|
| 37 |
+
border = styles.Border(top=side, right=side, bottom=side, left=side)
|
| 38 |
+
alignment = styles.Alignment(horizontal="center", vertical="top")
|
| 39 |
+
fill_color = styles.Color(rgb="006666FF", tint=0.3)
|
| 40 |
+
fill = styles.PatternFill(patternType="solid", fgColor=fill_color)
|
| 41 |
+
|
| 42 |
+
number_format = "0.00"
|
| 43 |
+
|
| 44 |
+
protection = styles.Protection(locked=True, hidden=False)
|
| 45 |
+
|
| 46 |
+
kw = _OpenpyxlWriter._convert_to_style_kwargs(hstyle)
|
| 47 |
+
assert kw["font"] == font
|
| 48 |
+
assert kw["border"] == border
|
| 49 |
+
assert kw["alignment"] == alignment
|
| 50 |
+
assert kw["fill"] == fill
|
| 51 |
+
assert kw["number_format"] == number_format
|
| 52 |
+
assert kw["protection"] == protection
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_write_cells_merge_styled(ext):
|
| 56 |
+
from pandas.io.formats.excel import ExcelCell
|
| 57 |
+
|
| 58 |
+
sheet_name = "merge_styled"
|
| 59 |
+
|
| 60 |
+
sty_b1 = {"font": {"color": "00FF0000"}}
|
| 61 |
+
sty_a2 = {"font": {"color": "0000FF00"}}
|
| 62 |
+
|
| 63 |
+
initial_cells = [
|
| 64 |
+
ExcelCell(col=1, row=0, val=42, style=sty_b1),
|
| 65 |
+
ExcelCell(col=0, row=1, val=99, style=sty_a2),
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
sty_merged = {"font": {"color": "000000FF", "bold": True}}
|
| 69 |
+
sty_kwargs = _OpenpyxlWriter._convert_to_style_kwargs(sty_merged)
|
| 70 |
+
openpyxl_sty_merged = sty_kwargs["font"]
|
| 71 |
+
merge_cells = [
|
| 72 |
+
ExcelCell(
|
| 73 |
+
col=0, row=0, val="pandas", mergestart=1, mergeend=1, style=sty_merged
|
| 74 |
+
)
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
with tm.ensure_clean(ext) as path:
|
| 78 |
+
with _OpenpyxlWriter(path) as writer:
|
| 79 |
+
writer._write_cells(initial_cells, sheet_name=sheet_name)
|
| 80 |
+
writer._write_cells(merge_cells, sheet_name=sheet_name)
|
| 81 |
+
|
| 82 |
+
wks = writer.sheets[sheet_name]
|
| 83 |
+
xcell_b1 = wks["B1"]
|
| 84 |
+
xcell_a2 = wks["A2"]
|
| 85 |
+
assert xcell_b1.font == openpyxl_sty_merged
|
| 86 |
+
assert xcell_a2.font == openpyxl_sty_merged
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.mark.parametrize("iso_dates", [True, False])
|
| 90 |
+
def test_engine_kwargs_write(ext, iso_dates):
|
| 91 |
+
# GH 42286 GH 43445
|
| 92 |
+
engine_kwargs = {"iso_dates": iso_dates}
|
| 93 |
+
with tm.ensure_clean(ext) as f:
|
| 94 |
+
with ExcelWriter(f, engine="openpyxl", engine_kwargs=engine_kwargs) as writer:
|
| 95 |
+
assert writer.book.iso_dates == iso_dates
|
| 96 |
+
# ExcelWriter won't allow us to close without writing something
|
| 97 |
+
DataFrame().to_excel(writer)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_engine_kwargs_append_invalid(ext):
|
| 101 |
+
# GH 43445
|
| 102 |
+
# test whether an invalid engine kwargs actually raises
|
| 103 |
+
with tm.ensure_clean(ext) as f:
|
| 104 |
+
DataFrame(["hello", "world"]).to_excel(f)
|
| 105 |
+
with pytest.raises(
|
| 106 |
+
TypeError,
|
| 107 |
+
match=re.escape(
|
| 108 |
+
"load_workbook() got an unexpected keyword argument 'apple_banana'"
|
| 109 |
+
),
|
| 110 |
+
):
|
| 111 |
+
with ExcelWriter(
|
| 112 |
+
f, engine="openpyxl", mode="a", engine_kwargs={"apple_banana": "fruit"}
|
| 113 |
+
) as writer:
|
| 114 |
+
# ExcelWriter needs us to write something to close properly
|
| 115 |
+
DataFrame(["good"]).to_excel(writer, sheet_name="Sheet2")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@pytest.mark.parametrize("data_only, expected", [(True, 0), (False, "=1+1")])
|
| 119 |
+
def test_engine_kwargs_append_data_only(ext, data_only, expected):
|
| 120 |
+
# GH 43445
|
| 121 |
+
# tests whether the data_only engine_kwarg actually works well for
|
| 122 |
+
# openpyxl's load_workbook
|
| 123 |
+
with tm.ensure_clean(ext) as f:
|
| 124 |
+
DataFrame(["=1+1"]).to_excel(f)
|
| 125 |
+
with ExcelWriter(
|
| 126 |
+
f, engine="openpyxl", mode="a", engine_kwargs={"data_only": data_only}
|
| 127 |
+
) as writer:
|
| 128 |
+
assert writer.sheets["Sheet1"]["B2"].value == expected
|
| 129 |
+
# ExcelWriter needs us to writer something to close properly?
|
| 130 |
+
DataFrame().to_excel(writer, sheet_name="Sheet2")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@pytest.mark.parametrize(
|
| 134 |
+
"mode,expected", [("w", ["baz"]), ("a", ["foo", "bar", "baz"])]
|
| 135 |
+
)
|
| 136 |
+
def test_write_append_mode(ext, mode, expected):
|
| 137 |
+
df = DataFrame([1], columns=["baz"])
|
| 138 |
+
|
| 139 |
+
with tm.ensure_clean(ext) as f:
|
| 140 |
+
wb = openpyxl.Workbook()
|
| 141 |
+
wb.worksheets[0].title = "foo"
|
| 142 |
+
wb.worksheets[0]["A1"].value = "foo"
|
| 143 |
+
wb.create_sheet("bar")
|
| 144 |
+
wb.worksheets[1]["A1"].value = "bar"
|
| 145 |
+
wb.save(f)
|
| 146 |
+
|
| 147 |
+
with ExcelWriter(f, engine="openpyxl", mode=mode) as writer:
|
| 148 |
+
df.to_excel(writer, sheet_name="baz", index=False)
|
| 149 |
+
|
| 150 |
+
with contextlib.closing(openpyxl.load_workbook(f)) as wb2:
|
| 151 |
+
result = [sheet.title for sheet in wb2.worksheets]
|
| 152 |
+
assert result == expected
|
| 153 |
+
|
| 154 |
+
for index, cell_value in enumerate(expected):
|
| 155 |
+
assert wb2.worksheets[index]["A1"].value == cell_value
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize(
|
| 159 |
+
"if_sheet_exists,num_sheets,expected",
|
| 160 |
+
[
|
| 161 |
+
("new", 2, ["apple", "banana"]),
|
| 162 |
+
("replace", 1, ["pear"]),
|
| 163 |
+
("overlay", 1, ["pear", "banana"]),
|
| 164 |
+
],
|
| 165 |
+
)
|
| 166 |
+
def test_if_sheet_exists_append_modes(ext, if_sheet_exists, num_sheets, expected):
|
| 167 |
+
# GH 40230
|
| 168 |
+
df1 = DataFrame({"fruit": ["apple", "banana"]})
|
| 169 |
+
df2 = DataFrame({"fruit": ["pear"]})
|
| 170 |
+
|
| 171 |
+
with tm.ensure_clean(ext) as f:
|
| 172 |
+
df1.to_excel(f, engine="openpyxl", sheet_name="foo", index=False)
|
| 173 |
+
with ExcelWriter(
|
| 174 |
+
f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists
|
| 175 |
+
) as writer:
|
| 176 |
+
df2.to_excel(writer, sheet_name="foo", index=False)
|
| 177 |
+
|
| 178 |
+
with contextlib.closing(openpyxl.load_workbook(f)) as wb:
|
| 179 |
+
assert len(wb.sheetnames) == num_sheets
|
| 180 |
+
assert wb.sheetnames[0] == "foo"
|
| 181 |
+
result = pd.read_excel(wb, "foo", engine="openpyxl")
|
| 182 |
+
assert list(result["fruit"]) == expected
|
| 183 |
+
if len(wb.sheetnames) == 2:
|
| 184 |
+
result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl")
|
| 185 |
+
tm.assert_frame_equal(result, df2)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@pytest.mark.parametrize(
|
| 189 |
+
"startrow, startcol, greeting, goodbye",
|
| 190 |
+
[
|
| 191 |
+
(0, 0, ["poop", "world"], ["goodbye", "people"]),
|
| 192 |
+
(0, 1, ["hello", "world"], ["poop", "people"]),
|
| 193 |
+
(1, 0, ["hello", "poop"], ["goodbye", "people"]),
|
| 194 |
+
(1, 1, ["hello", "world"], ["goodbye", "poop"]),
|
| 195 |
+
],
|
| 196 |
+
)
|
| 197 |
+
def test_append_overlay_startrow_startcol(ext, startrow, startcol, greeting, goodbye):
|
| 198 |
+
df1 = DataFrame({"greeting": ["hello", "world"], "goodbye": ["goodbye", "people"]})
|
| 199 |
+
df2 = DataFrame(["poop"])
|
| 200 |
+
|
| 201 |
+
with tm.ensure_clean(ext) as f:
|
| 202 |
+
df1.to_excel(f, engine="openpyxl", sheet_name="poo", index=False)
|
| 203 |
+
with ExcelWriter(
|
| 204 |
+
f, engine="openpyxl", mode="a", if_sheet_exists="overlay"
|
| 205 |
+
) as writer:
|
| 206 |
+
# use startrow+1 because we don't have a header
|
| 207 |
+
df2.to_excel(
|
| 208 |
+
writer,
|
| 209 |
+
index=False,
|
| 210 |
+
header=False,
|
| 211 |
+
startrow=startrow + 1,
|
| 212 |
+
startcol=startcol,
|
| 213 |
+
sheet_name="poo",
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
result = pd.read_excel(f, sheet_name="poo", engine="openpyxl")
|
| 217 |
+
expected = DataFrame({"greeting": greeting, "goodbye": goodbye})
|
| 218 |
+
tm.assert_frame_equal(result, expected)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@pytest.mark.parametrize(
|
| 222 |
+
"if_sheet_exists,msg",
|
| 223 |
+
[
|
| 224 |
+
(
|
| 225 |
+
"invalid",
|
| 226 |
+
"'invalid' is not valid for if_sheet_exists. Valid options "
|
| 227 |
+
"are 'error', 'new', 'replace' and 'overlay'.",
|
| 228 |
+
),
|
| 229 |
+
(
|
| 230 |
+
"error",
|
| 231 |
+
"Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",
|
| 232 |
+
),
|
| 233 |
+
(
|
| 234 |
+
None,
|
| 235 |
+
"Sheet 'foo' already exists and if_sheet_exists is set to 'error'.",
|
| 236 |
+
),
|
| 237 |
+
],
|
| 238 |
+
)
|
| 239 |
+
def test_if_sheet_exists_raises(ext, if_sheet_exists, msg):
|
| 240 |
+
# GH 40230
|
| 241 |
+
df = DataFrame({"fruit": ["pear"]})
|
| 242 |
+
with tm.ensure_clean(ext) as f:
|
| 243 |
+
with pytest.raises(ValueError, match=re.escape(msg)):
|
| 244 |
+
df.to_excel(f, "foo", engine="openpyxl")
|
| 245 |
+
with ExcelWriter(
|
| 246 |
+
f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists
|
| 247 |
+
) as writer:
|
| 248 |
+
df.to_excel(writer, sheet_name="foo")
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def test_to_excel_with_openpyxl_engine(ext):
|
| 252 |
+
# GH 29854
|
| 253 |
+
with tm.ensure_clean(ext) as filename:
|
| 254 |
+
df1 = DataFrame({"A": np.linspace(1, 10, 10)})
|
| 255 |
+
df2 = DataFrame({"B": np.linspace(1, 20, 10)})
|
| 256 |
+
df = pd.concat([df1, df2], axis=1)
|
| 257 |
+
styled = df.style.applymap(
|
| 258 |
+
lambda val: f"color: {'red' if val < 0 else 'black'}"
|
| 259 |
+
).highlight_max()
|
| 260 |
+
|
| 261 |
+
styled.to_excel(filename, engine="openpyxl")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
@pytest.mark.parametrize("read_only", [True, False])
|
| 265 |
+
def test_read_workbook(datapath, ext, read_only):
|
| 266 |
+
# GH 39528
|
| 267 |
+
filename = datapath("io", "data", "excel", "test1" + ext)
|
| 268 |
+
with contextlib.closing(
|
| 269 |
+
openpyxl.load_workbook(filename, read_only=read_only)
|
| 270 |
+
) as wb:
|
| 271 |
+
result = pd.read_excel(wb, engine="openpyxl")
|
| 272 |
+
expected = pd.read_excel(filename)
|
| 273 |
+
tm.assert_frame_equal(result, expected)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@pytest.mark.parametrize(
|
| 277 |
+
"header, expected_data",
|
| 278 |
+
[
|
| 279 |
+
(
|
| 280 |
+
0,
|
| 281 |
+
{
|
| 282 |
+
"Title": [np.nan, "A", 1, 2, 3],
|
| 283 |
+
"Unnamed: 1": [np.nan, "B", 4, 5, 6],
|
| 284 |
+
"Unnamed: 2": [np.nan, "C", 7, 8, 9],
|
| 285 |
+
},
|
| 286 |
+
),
|
| 287 |
+
(2, {"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}),
|
| 288 |
+
],
|
| 289 |
+
)
|
| 290 |
+
@pytest.mark.parametrize(
|
| 291 |
+
"filename", ["dimension_missing", "dimension_small", "dimension_large"]
|
| 292 |
+
)
|
| 293 |
+
# When read_only is None, use read_excel instead of a workbook
|
| 294 |
+
@pytest.mark.parametrize("read_only", [True, False, None])
|
| 295 |
+
def test_read_with_bad_dimension(
|
| 296 |
+
datapath, ext, header, expected_data, filename, read_only
|
| 297 |
+
):
|
| 298 |
+
# GH 38956, 39001 - no/incorrect dimension information
|
| 299 |
+
path = datapath("io", "data", "excel", f"{filename}{ext}")
|
| 300 |
+
if read_only is None:
|
| 301 |
+
result = pd.read_excel(path, header=header)
|
| 302 |
+
else:
|
| 303 |
+
with contextlib.closing(
|
| 304 |
+
openpyxl.load_workbook(path, read_only=read_only)
|
| 305 |
+
) as wb:
|
| 306 |
+
result = pd.read_excel(wb, engine="openpyxl", header=header)
|
| 307 |
+
expected = DataFrame(expected_data)
|
| 308 |
+
tm.assert_frame_equal(result, expected)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def test_append_mode_file(ext):
|
| 312 |
+
# GH 39576
|
| 313 |
+
df = DataFrame()
|
| 314 |
+
|
| 315 |
+
with tm.ensure_clean(ext) as f:
|
| 316 |
+
df.to_excel(f, engine="openpyxl")
|
| 317 |
+
|
| 318 |
+
with ExcelWriter(
|
| 319 |
+
f, mode="a", engine="openpyxl", if_sheet_exists="new"
|
| 320 |
+
) as writer:
|
| 321 |
+
df.to_excel(writer)
|
| 322 |
+
|
| 323 |
+
# make sure that zip files are not concatenated by making sure that
|
| 324 |
+
# "docProps/app.xml" only occurs twice in the file
|
| 325 |
+
data = Path(f).read_bytes()
|
| 326 |
+
first = data.find(b"docProps/app.xml")
|
| 327 |
+
second = data.find(b"docProps/app.xml", first + 1)
|
| 328 |
+
third = data.find(b"docProps/app.xml", second + 1)
|
| 329 |
+
assert second != -1 and third == -1
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# When read_only is None, use read_excel instead of a workbook
|
| 333 |
+
@pytest.mark.parametrize("read_only", [True, False, None])
|
| 334 |
+
def test_read_with_empty_trailing_rows(datapath, ext, read_only):
|
| 335 |
+
# GH 39181
|
| 336 |
+
path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}")
|
| 337 |
+
if read_only is None:
|
| 338 |
+
result = pd.read_excel(path)
|
| 339 |
+
else:
|
| 340 |
+
with contextlib.closing(
|
| 341 |
+
openpyxl.load_workbook(path, read_only=read_only)
|
| 342 |
+
) as wb:
|
| 343 |
+
result = pd.read_excel(wb, engine="openpyxl")
|
| 344 |
+
expected = DataFrame(
|
| 345 |
+
{
|
| 346 |
+
"Title": [np.nan, "A", 1, 2, 3],
|
| 347 |
+
"Unnamed: 1": [np.nan, "B", 4, 5, 6],
|
| 348 |
+
"Unnamed: 2": [np.nan, "C", 7, 8, 9],
|
| 349 |
+
}
|
| 350 |
+
)
|
| 351 |
+
tm.assert_frame_equal(result, expected)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# When read_only is None, use read_excel instead of a workbook
|
| 355 |
+
@pytest.mark.parametrize("read_only", [True, False, None])
|
| 356 |
+
def test_read_empty_with_blank_row(datapath, ext, read_only):
|
| 357 |
+
# GH 39547 - empty excel file with a row that has no data
|
| 358 |
+
path = datapath("io", "data", "excel", f"empty_with_blank_row{ext}")
|
| 359 |
+
if read_only is None:
|
| 360 |
+
result = pd.read_excel(path)
|
| 361 |
+
else:
|
| 362 |
+
with contextlib.closing(
|
| 363 |
+
openpyxl.load_workbook(path, read_only=read_only)
|
| 364 |
+
) as wb:
|
| 365 |
+
result = pd.read_excel(wb, engine="openpyxl")
|
| 366 |
+
expected = DataFrame()
|
| 367 |
+
tm.assert_frame_equal(result, expected)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def test_book_and_sheets_consistent(ext):
|
| 371 |
+
# GH#45687 - Ensure sheets is updated if user modifies book
|
| 372 |
+
with tm.ensure_clean(ext) as f:
|
| 373 |
+
with ExcelWriter(f, engine="openpyxl") as writer:
|
| 374 |
+
assert writer.sheets == {}
|
| 375 |
+
sheet = writer.book.create_sheet("test_name", 0)
|
| 376 |
+
assert writer.sheets == {"test_name": sheet}
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def test_ints_spelled_with_decimals(datapath, ext):
|
| 380 |
+
# GH 46988 - openpyxl returns this sheet with floats
|
| 381 |
+
path = datapath("io", "data", "excel", f"ints_spelled_with_decimals{ext}")
|
| 382 |
+
result = pd.read_excel(path)
|
| 383 |
+
expected = DataFrame(range(2, 12), columns=[1])
|
| 384 |
+
tm.assert_frame_equal(result, expected)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def test_read_multiindex_header_no_index_names(datapath, ext):
|
| 388 |
+
# GH#47487
|
| 389 |
+
path = datapath("io", "data", "excel", f"multiindex_no_index_names{ext}")
|
| 390 |
+
result = pd.read_excel(path, index_col=[0, 1, 2], header=[0, 1, 2])
|
| 391 |
+
expected = DataFrame(
|
| 392 |
+
[[np.nan, "x", "x", "x"], ["x", np.nan, np.nan, np.nan]],
|
| 393 |
+
columns=pd.MultiIndex.from_tuples(
|
| 394 |
+
[("X", "Y", "A1"), ("X", "Y", "A2"), ("XX", "YY", "B1"), ("XX", "YY", "B2")]
|
| 395 |
+
),
|
| 396 |
+
index=pd.MultiIndex.from_tuples([("A", "AA", "AAA"), ("A", "BB", "BBB")]),
|
| 397 |
+
)
|
| 398 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_readers.py
ADDED
|
@@ -0,0 +1,1674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import (
|
| 2 |
+
datetime,
|
| 3 |
+
time,
|
| 4 |
+
)
|
| 5 |
+
from functools import partial
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import platform
|
| 9 |
+
from urllib.error import URLError
|
| 10 |
+
from zipfile import BadZipFile
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
import pandas.util._test_decorators as td
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
from pandas import (
|
| 19 |
+
DataFrame,
|
| 20 |
+
Index,
|
| 21 |
+
MultiIndex,
|
| 22 |
+
Series,
|
| 23 |
+
)
|
| 24 |
+
import pandas._testing as tm
|
| 25 |
+
from pandas.core.arrays import (
|
| 26 |
+
ArrowStringArray,
|
| 27 |
+
StringArray,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"]
|
| 31 |
+
engine_params = [
|
| 32 |
+
# Add any engines to test here
|
| 33 |
+
# When defusedxml is installed it triggers deprecation warnings for
|
| 34 |
+
# xlrd and openpyxl, so catch those here
|
| 35 |
+
pytest.param(
|
| 36 |
+
"xlrd",
|
| 37 |
+
marks=[
|
| 38 |
+
td.skip_if_no("xlrd"),
|
| 39 |
+
],
|
| 40 |
+
),
|
| 41 |
+
pytest.param(
|
| 42 |
+
"openpyxl",
|
| 43 |
+
marks=[
|
| 44 |
+
td.skip_if_no("openpyxl"),
|
| 45 |
+
],
|
| 46 |
+
),
|
| 47 |
+
pytest.param(
|
| 48 |
+
None,
|
| 49 |
+
marks=[
|
| 50 |
+
td.skip_if_no("xlrd"),
|
| 51 |
+
],
|
| 52 |
+
),
|
| 53 |
+
pytest.param("pyxlsb", marks=td.skip_if_no("pyxlsb")),
|
| 54 |
+
pytest.param("odf", marks=td.skip_if_no("odf")),
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _is_valid_engine_ext_pair(engine, read_ext: str) -> bool:
|
| 59 |
+
"""
|
| 60 |
+
Filter out invalid (engine, ext) pairs instead of skipping, as that
|
| 61 |
+
produces 500+ pytest.skips.
|
| 62 |
+
"""
|
| 63 |
+
engine = engine.values[0]
|
| 64 |
+
if engine == "openpyxl" and read_ext == ".xls":
|
| 65 |
+
return False
|
| 66 |
+
if engine == "odf" and read_ext != ".ods":
|
| 67 |
+
return False
|
| 68 |
+
if read_ext == ".ods" and engine != "odf":
|
| 69 |
+
return False
|
| 70 |
+
if engine == "pyxlsb" and read_ext != ".xlsb":
|
| 71 |
+
return False
|
| 72 |
+
if read_ext == ".xlsb" and engine != "pyxlsb":
|
| 73 |
+
return False
|
| 74 |
+
if engine == "xlrd" and read_ext != ".xls":
|
| 75 |
+
return False
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _transfer_marks(engine, read_ext):
|
| 80 |
+
"""
|
| 81 |
+
engine gives us a pytest.param object with some marks, read_ext is just
|
| 82 |
+
a string. We need to generate a new pytest.param inheriting the marks.
|
| 83 |
+
"""
|
| 84 |
+
values = engine.values + (read_ext,)
|
| 85 |
+
new_param = pytest.param(values, marks=engine.marks)
|
| 86 |
+
return new_param
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.fixture(
|
| 90 |
+
params=[
|
| 91 |
+
_transfer_marks(eng, ext)
|
| 92 |
+
for eng in engine_params
|
| 93 |
+
for ext in read_ext_params
|
| 94 |
+
if _is_valid_engine_ext_pair(eng, ext)
|
| 95 |
+
],
|
| 96 |
+
ids=str,
|
| 97 |
+
)
|
| 98 |
+
def engine_and_read_ext(request):
|
| 99 |
+
"""
|
| 100 |
+
Fixture for Excel reader engine and read_ext, only including valid pairs.
|
| 101 |
+
"""
|
| 102 |
+
return request.param
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.fixture
|
| 106 |
+
def engine(engine_and_read_ext):
|
| 107 |
+
engine, read_ext = engine_and_read_ext
|
| 108 |
+
return engine
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@pytest.fixture
|
| 112 |
+
def read_ext(engine_and_read_ext):
|
| 113 |
+
engine, read_ext = engine_and_read_ext
|
| 114 |
+
return read_ext
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TestReaders:
|
| 118 |
+
@pytest.fixture(autouse=True)
|
| 119 |
+
def cd_and_set_engine(self, engine, datapath, monkeypatch):
|
| 120 |
+
"""
|
| 121 |
+
Change directory and set engine for read_excel calls.
|
| 122 |
+
"""
|
| 123 |
+
func = partial(pd.read_excel, engine=engine)
|
| 124 |
+
monkeypatch.chdir(datapath("io", "data", "excel"))
|
| 125 |
+
monkeypatch.setattr(pd, "read_excel", func)
|
| 126 |
+
|
| 127 |
+
def test_engine_used(self, read_ext, engine, monkeypatch):
|
| 128 |
+
# GH 38884
|
| 129 |
+
def parser(self, *args, **kwargs):
|
| 130 |
+
return self.engine
|
| 131 |
+
|
| 132 |
+
monkeypatch.setattr(pd.ExcelFile, "parse", parser)
|
| 133 |
+
|
| 134 |
+
expected_defaults = {
|
| 135 |
+
"xlsx": "openpyxl",
|
| 136 |
+
"xlsm": "openpyxl",
|
| 137 |
+
"xlsb": "pyxlsb",
|
| 138 |
+
"xls": "xlrd",
|
| 139 |
+
"ods": "odf",
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
with open("test1" + read_ext, "rb") as f:
|
| 143 |
+
result = pd.read_excel(f)
|
| 144 |
+
|
| 145 |
+
if engine is not None:
|
| 146 |
+
expected = engine
|
| 147 |
+
else:
|
| 148 |
+
expected = expected_defaults[read_ext[1:]]
|
| 149 |
+
assert result == expected
|
| 150 |
+
|
| 151 |
+
def test_usecols_int(self, read_ext):
|
| 152 |
+
# usecols as int
|
| 153 |
+
msg = "Passing an integer for `usecols`"
|
| 154 |
+
with pytest.raises(ValueError, match=msg):
|
| 155 |
+
pd.read_excel(
|
| 156 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=3
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# usecols as int
|
| 160 |
+
with pytest.raises(ValueError, match=msg):
|
| 161 |
+
pd.read_excel(
|
| 162 |
+
"test1" + read_ext,
|
| 163 |
+
sheet_name="Sheet2",
|
| 164 |
+
skiprows=[1],
|
| 165 |
+
index_col=0,
|
| 166 |
+
usecols=3,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def test_usecols_list(self, request, read_ext, df_ref):
|
| 170 |
+
if read_ext == ".xlsb":
|
| 171 |
+
request.node.add_marker(
|
| 172 |
+
pytest.mark.xfail(
|
| 173 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
df_ref = df_ref.reindex(columns=["B", "C"])
|
| 178 |
+
df1 = pd.read_excel(
|
| 179 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=[0, 2, 3]
|
| 180 |
+
)
|
| 181 |
+
df2 = pd.read_excel(
|
| 182 |
+
"test1" + read_ext,
|
| 183 |
+
sheet_name="Sheet2",
|
| 184 |
+
skiprows=[1],
|
| 185 |
+
index_col=0,
|
| 186 |
+
usecols=[0, 2, 3],
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# TODO add index to xls file)
|
| 190 |
+
tm.assert_frame_equal(df1, df_ref, check_names=False)
|
| 191 |
+
tm.assert_frame_equal(df2, df_ref, check_names=False)
|
| 192 |
+
|
| 193 |
+
def test_usecols_str(self, request, read_ext, df_ref):
|
| 194 |
+
if read_ext == ".xlsb":
|
| 195 |
+
request.node.add_marker(
|
| 196 |
+
pytest.mark.xfail(
|
| 197 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 198 |
+
)
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
df1 = df_ref.reindex(columns=["A", "B", "C"])
|
| 202 |
+
df2 = pd.read_excel(
|
| 203 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A:D"
|
| 204 |
+
)
|
| 205 |
+
df3 = pd.read_excel(
|
| 206 |
+
"test1" + read_ext,
|
| 207 |
+
sheet_name="Sheet2",
|
| 208 |
+
skiprows=[1],
|
| 209 |
+
index_col=0,
|
| 210 |
+
usecols="A:D",
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# TODO add index to xls, read xls ignores index name ?
|
| 214 |
+
tm.assert_frame_equal(df2, df1, check_names=False)
|
| 215 |
+
tm.assert_frame_equal(df3, df1, check_names=False)
|
| 216 |
+
|
| 217 |
+
df1 = df_ref.reindex(columns=["B", "C"])
|
| 218 |
+
df2 = pd.read_excel(
|
| 219 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C,D"
|
| 220 |
+
)
|
| 221 |
+
df3 = pd.read_excel(
|
| 222 |
+
"test1" + read_ext,
|
| 223 |
+
sheet_name="Sheet2",
|
| 224 |
+
skiprows=[1],
|
| 225 |
+
index_col=0,
|
| 226 |
+
usecols="A,C,D",
|
| 227 |
+
)
|
| 228 |
+
# TODO add index to xls file
|
| 229 |
+
tm.assert_frame_equal(df2, df1, check_names=False)
|
| 230 |
+
tm.assert_frame_equal(df3, df1, check_names=False)
|
| 231 |
+
|
| 232 |
+
df1 = df_ref.reindex(columns=["B", "C"])
|
| 233 |
+
df2 = pd.read_excel(
|
| 234 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C:D"
|
| 235 |
+
)
|
| 236 |
+
df3 = pd.read_excel(
|
| 237 |
+
"test1" + read_ext,
|
| 238 |
+
sheet_name="Sheet2",
|
| 239 |
+
skiprows=[1],
|
| 240 |
+
index_col=0,
|
| 241 |
+
usecols="A,C:D",
|
| 242 |
+
)
|
| 243 |
+
tm.assert_frame_equal(df2, df1, check_names=False)
|
| 244 |
+
tm.assert_frame_equal(df3, df1, check_names=False)
|
| 245 |
+
|
| 246 |
+
@pytest.mark.parametrize(
|
| 247 |
+
"usecols", [[0, 1, 3], [0, 3, 1], [1, 0, 3], [1, 3, 0], [3, 0, 1], [3, 1, 0]]
|
| 248 |
+
)
|
| 249 |
+
def test_usecols_diff_positional_int_columns_order(
|
| 250 |
+
self, request, read_ext, usecols, df_ref
|
| 251 |
+
):
|
| 252 |
+
if read_ext == ".xlsb":
|
| 253 |
+
request.node.add_marker(
|
| 254 |
+
pytest.mark.xfail(
|
| 255 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 256 |
+
)
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
expected = df_ref[["A", "C"]]
|
| 260 |
+
result = pd.read_excel(
|
| 261 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=usecols
|
| 262 |
+
)
|
| 263 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 264 |
+
|
| 265 |
+
@pytest.mark.parametrize("usecols", [["B", "D"], ["D", "B"]])
|
| 266 |
+
def test_usecols_diff_positional_str_columns_order(self, read_ext, usecols, df_ref):
|
| 267 |
+
expected = df_ref[["B", "D"]]
|
| 268 |
+
expected.index = range(len(expected))
|
| 269 |
+
|
| 270 |
+
result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols=usecols)
|
| 271 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 272 |
+
|
| 273 |
+
def test_read_excel_without_slicing(self, request, read_ext, df_ref):
|
| 274 |
+
if read_ext == ".xlsb":
|
| 275 |
+
request.node.add_marker(
|
| 276 |
+
pytest.mark.xfail(
|
| 277 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 278 |
+
)
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
expected = df_ref
|
| 282 |
+
result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)
|
| 283 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 284 |
+
|
| 285 |
+
def test_usecols_excel_range_str(self, request, read_ext, df_ref):
|
| 286 |
+
if read_ext == ".xlsb":
|
| 287 |
+
request.node.add_marker(
|
| 288 |
+
pytest.mark.xfail(
|
| 289 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 290 |
+
)
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
expected = df_ref[["C", "D"]]
|
| 294 |
+
result = pd.read_excel(
|
| 295 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,D:E"
|
| 296 |
+
)
|
| 297 |
+
tm.assert_frame_equal(result, expected, check_names=False)
|
| 298 |
+
|
| 299 |
+
def test_usecols_excel_range_str_invalid(self, read_ext):
|
| 300 |
+
msg = "Invalid column name: E1"
|
| 301 |
+
|
| 302 |
+
with pytest.raises(ValueError, match=msg):
|
| 303 |
+
pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols="D:E1")
|
| 304 |
+
|
| 305 |
+
def test_index_col_label_error(self, read_ext):
|
| 306 |
+
msg = "list indices must be integers.*, not str"
|
| 307 |
+
|
| 308 |
+
with pytest.raises(TypeError, match=msg):
|
| 309 |
+
pd.read_excel(
|
| 310 |
+
"test1" + read_ext,
|
| 311 |
+
sheet_name="Sheet1",
|
| 312 |
+
index_col=["A"],
|
| 313 |
+
usecols=["A", "C"],
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
def test_index_col_empty(self, read_ext):
|
| 317 |
+
# see gh-9208
|
| 318 |
+
result = pd.read_excel(
|
| 319 |
+
"test1" + read_ext, sheet_name="Sheet3", index_col=["A", "B", "C"]
|
| 320 |
+
)
|
| 321 |
+
expected = DataFrame(
|
| 322 |
+
columns=["D", "E", "F"],
|
| 323 |
+
index=MultiIndex(levels=[[]] * 3, codes=[[]] * 3, names=["A", "B", "C"]),
|
| 324 |
+
)
|
| 325 |
+
tm.assert_frame_equal(result, expected)
|
| 326 |
+
|
| 327 |
+
@pytest.mark.parametrize("index_col", [None, 2])
|
| 328 |
+
def test_index_col_with_unnamed(self, read_ext, index_col):
|
| 329 |
+
# see gh-18792
|
| 330 |
+
result = pd.read_excel(
|
| 331 |
+
"test1" + read_ext, sheet_name="Sheet4", index_col=index_col
|
| 332 |
+
)
|
| 333 |
+
expected = DataFrame(
|
| 334 |
+
[["i1", "a", "x"], ["i2", "b", "y"]], columns=["Unnamed: 0", "col1", "col2"]
|
| 335 |
+
)
|
| 336 |
+
if index_col:
|
| 337 |
+
expected = expected.set_index(expected.columns[index_col])
|
| 338 |
+
|
| 339 |
+
tm.assert_frame_equal(result, expected)
|
| 340 |
+
|
| 341 |
+
def test_usecols_pass_non_existent_column(self, read_ext):
|
| 342 |
+
msg = (
|
| 343 |
+
"Usecols do not match columns, "
|
| 344 |
+
"columns expected but not found: " + r"\['E'\]"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
with pytest.raises(ValueError, match=msg):
|
| 348 |
+
pd.read_excel("test1" + read_ext, usecols=["E"])
|
| 349 |
+
|
| 350 |
+
def test_usecols_wrong_type(self, read_ext):
|
| 351 |
+
msg = (
|
| 352 |
+
"'usecols' must either be list-like of "
|
| 353 |
+
"all strings, all unicode, all integers or a callable."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
with pytest.raises(ValueError, match=msg):
|
| 357 |
+
pd.read_excel("test1" + read_ext, usecols=["E1", 0])
|
| 358 |
+
|
| 359 |
+
def test_excel_stop_iterator(self, read_ext):
|
| 360 |
+
parsed = pd.read_excel("test2" + read_ext, sheet_name="Sheet1")
|
| 361 |
+
expected = DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"])
|
| 362 |
+
tm.assert_frame_equal(parsed, expected)
|
| 363 |
+
|
| 364 |
+
def test_excel_cell_error_na(self, request, read_ext):
|
| 365 |
+
if read_ext == ".xlsb":
|
| 366 |
+
request.node.add_marker(
|
| 367 |
+
pytest.mark.xfail(
|
| 368 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 369 |
+
)
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
parsed = pd.read_excel("test3" + read_ext, sheet_name="Sheet1")
|
| 373 |
+
expected = DataFrame([[np.nan]], columns=["Test"])
|
| 374 |
+
tm.assert_frame_equal(parsed, expected)
|
| 375 |
+
|
| 376 |
+
def test_excel_table(self, request, read_ext, df_ref):
|
| 377 |
+
if read_ext == ".xlsb":
|
| 378 |
+
request.node.add_marker(
|
| 379 |
+
pytest.mark.xfail(
|
| 380 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 381 |
+
)
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)
|
| 385 |
+
df2 = pd.read_excel(
|
| 386 |
+
"test1" + read_ext, sheet_name="Sheet2", skiprows=[1], index_col=0
|
| 387 |
+
)
|
| 388 |
+
# TODO add index to file
|
| 389 |
+
tm.assert_frame_equal(df1, df_ref, check_names=False)
|
| 390 |
+
tm.assert_frame_equal(df2, df_ref, check_names=False)
|
| 391 |
+
|
| 392 |
+
df3 = pd.read_excel(
|
| 393 |
+
"test1" + read_ext, sheet_name="Sheet1", index_col=0, skipfooter=1
|
| 394 |
+
)
|
| 395 |
+
tm.assert_frame_equal(df3, df1.iloc[:-1])
|
| 396 |
+
|
| 397 |
+
def test_reader_special_dtypes(self, request, read_ext):
|
| 398 |
+
if read_ext == ".xlsb":
|
| 399 |
+
request.node.add_marker(
|
| 400 |
+
pytest.mark.xfail(
|
| 401 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 402 |
+
)
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
expected = DataFrame.from_dict(
|
| 406 |
+
{
|
| 407 |
+
"IntCol": [1, 2, -3, 4, 0],
|
| 408 |
+
"FloatCol": [1.25, 2.25, 1.83, 1.92, 0.0000000005],
|
| 409 |
+
"BoolCol": [True, False, True, True, False],
|
| 410 |
+
"StrCol": [1, 2, 3, 4, 5],
|
| 411 |
+
"Str2Col": ["a", 3, "c", "d", "e"],
|
| 412 |
+
"DateCol": [
|
| 413 |
+
datetime(2013, 10, 30),
|
| 414 |
+
datetime(2013, 10, 31),
|
| 415 |
+
datetime(1905, 1, 1),
|
| 416 |
+
datetime(2013, 12, 14),
|
| 417 |
+
datetime(2015, 3, 14),
|
| 418 |
+
],
|
| 419 |
+
},
|
| 420 |
+
)
|
| 421 |
+
basename = "test_types"
|
| 422 |
+
|
| 423 |
+
# should read in correctly and infer types
|
| 424 |
+
actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1")
|
| 425 |
+
tm.assert_frame_equal(actual, expected)
|
| 426 |
+
|
| 427 |
+
# if not coercing number, then int comes in as float
|
| 428 |
+
float_expected = expected.copy()
|
| 429 |
+
float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0
|
| 430 |
+
actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1")
|
| 431 |
+
tm.assert_frame_equal(actual, float_expected)
|
| 432 |
+
|
| 433 |
+
# check setting Index (assuming xls and xlsx are the same here)
|
| 434 |
+
for icol, name in enumerate(expected.columns):
|
| 435 |
+
actual = pd.read_excel(
|
| 436 |
+
basename + read_ext, sheet_name="Sheet1", index_col=icol
|
| 437 |
+
)
|
| 438 |
+
exp = expected.set_index(name)
|
| 439 |
+
tm.assert_frame_equal(actual, exp)
|
| 440 |
+
|
| 441 |
+
expected["StrCol"] = expected["StrCol"].apply(str)
|
| 442 |
+
actual = pd.read_excel(
|
| 443 |
+
basename + read_ext, sheet_name="Sheet1", converters={"StrCol": str}
|
| 444 |
+
)
|
| 445 |
+
tm.assert_frame_equal(actual, expected)
|
| 446 |
+
|
| 447 |
+
# GH8212 - support for converters and missing values
|
| 448 |
+
def test_reader_converters(self, read_ext):
|
| 449 |
+
basename = "test_converters"
|
| 450 |
+
|
| 451 |
+
expected = DataFrame.from_dict(
|
| 452 |
+
{
|
| 453 |
+
"IntCol": [1, 2, -3, -1000, 0],
|
| 454 |
+
"FloatCol": [12.5, np.nan, 18.3, 19.2, 0.000000005],
|
| 455 |
+
"BoolCol": ["Found", "Found", "Found", "Not found", "Found"],
|
| 456 |
+
"StrCol": ["1", np.nan, "3", "4", "5"],
|
| 457 |
+
}
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
converters = {
|
| 461 |
+
"IntCol": lambda x: int(x) if x != "" else -1000,
|
| 462 |
+
"FloatCol": lambda x: 10 * x if x else np.nan,
|
| 463 |
+
2: lambda x: "Found" if x != "" else "Not found",
|
| 464 |
+
3: lambda x: str(x) if x else "",
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
# should read in correctly and set types of single cells (not array
|
| 468 |
+
# dtypes)
|
| 469 |
+
actual = pd.read_excel(
|
| 470 |
+
basename + read_ext, sheet_name="Sheet1", converters=converters
|
| 471 |
+
)
|
| 472 |
+
tm.assert_frame_equal(actual, expected)
|
| 473 |
+
|
| 474 |
+
def test_reader_dtype(self, read_ext):
|
| 475 |
+
# GH 8212
|
| 476 |
+
basename = "testdtype"
|
| 477 |
+
actual = pd.read_excel(basename + read_ext)
|
| 478 |
+
|
| 479 |
+
expected = DataFrame(
|
| 480 |
+
{
|
| 481 |
+
"a": [1, 2, 3, 4],
|
| 482 |
+
"b": [2.5, 3.5, 4.5, 5.5],
|
| 483 |
+
"c": [1, 2, 3, 4],
|
| 484 |
+
"d": [1.0, 2.0, np.nan, 4.0],
|
| 485 |
+
}
|
| 486 |
+
).reindex(columns=["a", "b", "c", "d"])
|
| 487 |
+
|
| 488 |
+
tm.assert_frame_equal(actual, expected)
|
| 489 |
+
|
| 490 |
+
actual = pd.read_excel(
|
| 491 |
+
basename + read_ext, dtype={"a": "float64", "b": "float32", "c": str}
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
expected["a"] = expected["a"].astype("float64")
|
| 495 |
+
expected["b"] = expected["b"].astype("float32")
|
| 496 |
+
expected["c"] = ["001", "002", "003", "004"]
|
| 497 |
+
tm.assert_frame_equal(actual, expected)
|
| 498 |
+
|
| 499 |
+
msg = "Unable to convert column d to type int64"
|
| 500 |
+
with pytest.raises(ValueError, match=msg):
|
| 501 |
+
pd.read_excel(basename + read_ext, dtype={"d": "int64"})
|
| 502 |
+
|
| 503 |
+
@pytest.mark.parametrize(
|
| 504 |
+
"dtype,expected",
|
| 505 |
+
[
|
| 506 |
+
(
|
| 507 |
+
None,
|
| 508 |
+
DataFrame(
|
| 509 |
+
{
|
| 510 |
+
"a": [1, 2, 3, 4],
|
| 511 |
+
"b": [2.5, 3.5, 4.5, 5.5],
|
| 512 |
+
"c": [1, 2, 3, 4],
|
| 513 |
+
"d": [1.0, 2.0, np.nan, 4.0],
|
| 514 |
+
}
|
| 515 |
+
),
|
| 516 |
+
),
|
| 517 |
+
(
|
| 518 |
+
{"a": "float64", "b": "float32", "c": str, "d": str},
|
| 519 |
+
DataFrame(
|
| 520 |
+
{
|
| 521 |
+
"a": Series([1, 2, 3, 4], dtype="float64"),
|
| 522 |
+
"b": Series([2.5, 3.5, 4.5, 5.5], dtype="float32"),
|
| 523 |
+
"c": ["001", "002", "003", "004"],
|
| 524 |
+
"d": ["1", "2", np.nan, "4"],
|
| 525 |
+
}
|
| 526 |
+
),
|
| 527 |
+
),
|
| 528 |
+
],
|
| 529 |
+
)
|
| 530 |
+
def test_reader_dtype_str(self, read_ext, dtype, expected):
|
| 531 |
+
# see gh-20377
|
| 532 |
+
basename = "testdtype"
|
| 533 |
+
|
| 534 |
+
actual = pd.read_excel(basename + read_ext, dtype=dtype)
|
| 535 |
+
tm.assert_frame_equal(actual, expected)
|
| 536 |
+
|
| 537 |
+
def test_dtype_backend(self, read_ext, dtype_backend):
|
| 538 |
+
# GH#36712
|
| 539 |
+
if read_ext in (".xlsb", ".xls"):
|
| 540 |
+
pytest.skip(f"No engine for filetype: '{read_ext}'")
|
| 541 |
+
|
| 542 |
+
df = DataFrame(
|
| 543 |
+
{
|
| 544 |
+
"a": Series([1, 3], dtype="Int64"),
|
| 545 |
+
"b": Series([2.5, 4.5], dtype="Float64"),
|
| 546 |
+
"c": Series([True, False], dtype="boolean"),
|
| 547 |
+
"d": Series(["a", "b"], dtype="string"),
|
| 548 |
+
"e": Series([pd.NA, 6], dtype="Int64"),
|
| 549 |
+
"f": Series([pd.NA, 7.5], dtype="Float64"),
|
| 550 |
+
"g": Series([pd.NA, True], dtype="boolean"),
|
| 551 |
+
"h": Series([pd.NA, "a"], dtype="string"),
|
| 552 |
+
"i": Series([pd.Timestamp("2019-12-31")] * 2),
|
| 553 |
+
"j": Series([pd.NA, pd.NA], dtype="Int64"),
|
| 554 |
+
}
|
| 555 |
+
)
|
| 556 |
+
with tm.ensure_clean(read_ext) as file_path:
|
| 557 |
+
df.to_excel(file_path, "test", index=False)
|
| 558 |
+
result = pd.read_excel(
|
| 559 |
+
file_path, sheet_name="test", dtype_backend=dtype_backend
|
| 560 |
+
)
|
| 561 |
+
if dtype_backend == "pyarrow":
|
| 562 |
+
import pyarrow as pa
|
| 563 |
+
|
| 564 |
+
from pandas.arrays import ArrowExtensionArray
|
| 565 |
+
|
| 566 |
+
expected = DataFrame(
|
| 567 |
+
{
|
| 568 |
+
col: ArrowExtensionArray(pa.array(df[col], from_pandas=True))
|
| 569 |
+
for col in df.columns
|
| 570 |
+
}
|
| 571 |
+
)
|
| 572 |
+
# pyarrow by default infers timestamp resolution as us, not ns
|
| 573 |
+
expected["i"] = ArrowExtensionArray(
|
| 574 |
+
expected["i"].array._data.cast(pa.timestamp(unit="us"))
|
| 575 |
+
)
|
| 576 |
+
# pyarrow supports a null type, so don't have to default to Int64
|
| 577 |
+
expected["j"] = ArrowExtensionArray(pa.array([None, None]))
|
| 578 |
+
else:
|
| 579 |
+
expected = df
|
| 580 |
+
tm.assert_frame_equal(result, expected)
|
| 581 |
+
|
| 582 |
+
def test_dtype_backend_and_dtype(self, read_ext):
|
| 583 |
+
# GH#36712
|
| 584 |
+
if read_ext in (".xlsb", ".xls"):
|
| 585 |
+
pytest.skip(f"No engine for filetype: '{read_ext}'")
|
| 586 |
+
|
| 587 |
+
df = DataFrame({"a": [np.nan, 1.0], "b": [2.5, np.nan]})
|
| 588 |
+
with tm.ensure_clean(read_ext) as file_path:
|
| 589 |
+
df.to_excel(file_path, "test", index=False)
|
| 590 |
+
result = pd.read_excel(
|
| 591 |
+
file_path,
|
| 592 |
+
sheet_name="test",
|
| 593 |
+
dtype_backend="numpy_nullable",
|
| 594 |
+
dtype="float64",
|
| 595 |
+
)
|
| 596 |
+
tm.assert_frame_equal(result, df)
|
| 597 |
+
|
| 598 |
+
@td.skip_if_no("pyarrow")
|
| 599 |
+
def test_dtype_backend_string(self, read_ext, string_storage):
|
| 600 |
+
# GH#36712
|
| 601 |
+
if read_ext in (".xlsb", ".xls"):
|
| 602 |
+
pytest.skip(f"No engine for filetype: '{read_ext}'")
|
| 603 |
+
|
| 604 |
+
import pyarrow as pa
|
| 605 |
+
|
| 606 |
+
with pd.option_context("mode.string_storage", string_storage):
|
| 607 |
+
df = DataFrame(
|
| 608 |
+
{
|
| 609 |
+
"a": np.array(["a", "b"], dtype=np.object_),
|
| 610 |
+
"b": np.array(["x", pd.NA], dtype=np.object_),
|
| 611 |
+
}
|
| 612 |
+
)
|
| 613 |
+
with tm.ensure_clean(read_ext) as file_path:
|
| 614 |
+
df.to_excel(file_path, "test", index=False)
|
| 615 |
+
result = pd.read_excel(
|
| 616 |
+
file_path, sheet_name="test", dtype_backend="numpy_nullable"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
if string_storage == "python":
|
| 620 |
+
expected = DataFrame(
|
| 621 |
+
{
|
| 622 |
+
"a": StringArray(np.array(["a", "b"], dtype=np.object_)),
|
| 623 |
+
"b": StringArray(np.array(["x", pd.NA], dtype=np.object_)),
|
| 624 |
+
}
|
| 625 |
+
)
|
| 626 |
+
else:
|
| 627 |
+
expected = DataFrame(
|
| 628 |
+
{
|
| 629 |
+
"a": ArrowStringArray(pa.array(["a", "b"])),
|
| 630 |
+
"b": ArrowStringArray(pa.array(["x", None])),
|
| 631 |
+
}
|
| 632 |
+
)
|
| 633 |
+
tm.assert_frame_equal(result, expected)
|
| 634 |
+
|
| 635 |
+
@pytest.mark.parametrize("dtypes, exp_value", [({}, "1"), ({"a.1": "int64"}, 1)])
|
| 636 |
+
def test_dtype_mangle_dup_cols(self, read_ext, dtypes, exp_value):
|
| 637 |
+
# GH#35211
|
| 638 |
+
basename = "df_mangle_dup_col_dtypes"
|
| 639 |
+
dtype_dict = {"a": str, **dtypes}
|
| 640 |
+
dtype_dict_copy = dtype_dict.copy()
|
| 641 |
+
# GH#42462
|
| 642 |
+
result = pd.read_excel(basename + read_ext, dtype=dtype_dict)
|
| 643 |
+
expected = DataFrame({"a": ["1"], "a.1": [exp_value]})
|
| 644 |
+
assert dtype_dict == dtype_dict_copy, "dtype dict changed"
|
| 645 |
+
tm.assert_frame_equal(result, expected)
|
| 646 |
+
|
| 647 |
+
def test_reader_spaces(self, read_ext):
|
| 648 |
+
# see gh-32207
|
| 649 |
+
basename = "test_spaces"
|
| 650 |
+
|
| 651 |
+
actual = pd.read_excel(basename + read_ext)
|
| 652 |
+
expected = DataFrame(
|
| 653 |
+
{
|
| 654 |
+
"testcol": [
|
| 655 |
+
"this is great",
|
| 656 |
+
"4 spaces",
|
| 657 |
+
"1 trailing ",
|
| 658 |
+
" 1 leading",
|
| 659 |
+
"2 spaces multiple times",
|
| 660 |
+
]
|
| 661 |
+
}
|
| 662 |
+
)
|
| 663 |
+
tm.assert_frame_equal(actual, expected)
|
| 664 |
+
|
| 665 |
+
# gh-36122, gh-35802
|
| 666 |
+
@pytest.mark.parametrize(
|
| 667 |
+
"basename,expected",
|
| 668 |
+
[
|
| 669 |
+
("gh-35802", DataFrame({"COLUMN": ["Test (1)"]})),
|
| 670 |
+
("gh-36122", DataFrame(columns=["got 2nd sa"])),
|
| 671 |
+
],
|
| 672 |
+
)
|
| 673 |
+
def test_read_excel_ods_nested_xml(self, engine, read_ext, basename, expected):
|
| 674 |
+
# see gh-35802
|
| 675 |
+
if engine != "odf":
|
| 676 |
+
pytest.skip(f"Skipped for engine: {engine}")
|
| 677 |
+
|
| 678 |
+
actual = pd.read_excel(basename + read_ext)
|
| 679 |
+
tm.assert_frame_equal(actual, expected)
|
| 680 |
+
|
| 681 |
+
def test_reading_all_sheets(self, read_ext):
|
| 682 |
+
# Test reading all sheet names by setting sheet_name to None,
|
| 683 |
+
# Ensure a dict is returned.
|
| 684 |
+
# See PR #9450
|
| 685 |
+
basename = "test_multisheet"
|
| 686 |
+
dfs = pd.read_excel(basename + read_ext, sheet_name=None)
|
| 687 |
+
# ensure this is not alphabetical to test order preservation
|
| 688 |
+
expected_keys = ["Charlie", "Alpha", "Beta"]
|
| 689 |
+
tm.assert_contains_all(expected_keys, dfs.keys())
|
| 690 |
+
# Issue 9930
|
| 691 |
+
# Ensure sheet order is preserved
|
| 692 |
+
assert expected_keys == list(dfs.keys())
|
| 693 |
+
|
| 694 |
+
def test_reading_multiple_specific_sheets(self, read_ext):
|
| 695 |
+
# Test reading specific sheet names by specifying a mixed list
|
| 696 |
+
# of integers and strings, and confirm that duplicated sheet
|
| 697 |
+
# references (positions/names) are removed properly.
|
| 698 |
+
# Ensure a dict is returned
|
| 699 |
+
# See PR #9450
|
| 700 |
+
basename = "test_multisheet"
|
| 701 |
+
# Explicitly request duplicates. Only the set should be returned.
|
| 702 |
+
expected_keys = [2, "Charlie", "Charlie"]
|
| 703 |
+
dfs = pd.read_excel(basename + read_ext, sheet_name=expected_keys)
|
| 704 |
+
expected_keys = list(set(expected_keys))
|
| 705 |
+
tm.assert_contains_all(expected_keys, dfs.keys())
|
| 706 |
+
assert len(expected_keys) == len(dfs.keys())
|
| 707 |
+
|
| 708 |
+
def test_reading_all_sheets_with_blank(self, read_ext):
|
| 709 |
+
# Test reading all sheet names by setting sheet_name to None,
|
| 710 |
+
# In the case where some sheets are blank.
|
| 711 |
+
# Issue #11711
|
| 712 |
+
basename = "blank_with_header"
|
| 713 |
+
dfs = pd.read_excel(basename + read_ext, sheet_name=None)
|
| 714 |
+
expected_keys = ["Sheet1", "Sheet2", "Sheet3"]
|
| 715 |
+
tm.assert_contains_all(expected_keys, dfs.keys())
|
| 716 |
+
|
| 717 |
+
# GH6403
|
| 718 |
+
def test_read_excel_blank(self, read_ext):
|
| 719 |
+
actual = pd.read_excel("blank" + read_ext, sheet_name="Sheet1")
|
| 720 |
+
tm.assert_frame_equal(actual, DataFrame())
|
| 721 |
+
|
| 722 |
+
def test_read_excel_blank_with_header(self, read_ext):
|
| 723 |
+
expected = DataFrame(columns=["col_1", "col_2"])
|
| 724 |
+
actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1")
|
| 725 |
+
tm.assert_frame_equal(actual, expected)
|
| 726 |
+
|
| 727 |
+
def test_exception_message_includes_sheet_name(self, read_ext):
|
| 728 |
+
# GH 48706
|
| 729 |
+
with pytest.raises(ValueError, match=r" \(sheet: Sheet1\)$"):
|
| 730 |
+
pd.read_excel("blank_with_header" + read_ext, header=[1], sheet_name=None)
|
| 731 |
+
with pytest.raises(ZeroDivisionError, match=r" \(sheet: Sheet1\)$"):
|
| 732 |
+
pd.read_excel("test1" + read_ext, usecols=lambda x: 1 / 0, sheet_name=None)
|
| 733 |
+
|
| 734 |
+
@pytest.mark.filterwarnings("ignore:Cell A4 is marked:UserWarning:openpyxl")
|
| 735 |
+
def test_date_conversion_overflow(self, request, engine, read_ext):
|
| 736 |
+
# GH 10001 : pandas.ExcelFile ignore parse_dates=False
|
| 737 |
+
if engine == "pyxlsb":
|
| 738 |
+
request.node.add_marker(
|
| 739 |
+
pytest.mark.xfail(
|
| 740 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 741 |
+
)
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
expected = DataFrame(
|
| 745 |
+
[
|
| 746 |
+
[pd.Timestamp("2016-03-12"), "Marc Johnson"],
|
| 747 |
+
[pd.Timestamp("2016-03-16"), "Jack Black"],
|
| 748 |
+
[1e20, "Timothy Brown"],
|
| 749 |
+
],
|
| 750 |
+
columns=["DateColWithBigInt", "StringCol"],
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
if engine == "openpyxl":
|
| 754 |
+
request.node.add_marker(
|
| 755 |
+
pytest.mark.xfail(reason="Maybe not supported by openpyxl")
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
if engine is None and read_ext in (".xlsx", ".xlsm"):
|
| 759 |
+
# GH 35029
|
| 760 |
+
request.node.add_marker(
|
| 761 |
+
pytest.mark.xfail(reason="Defaults to openpyxl, maybe not supported")
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
result = pd.read_excel("testdateoverflow" + read_ext)
|
| 765 |
+
tm.assert_frame_equal(result, expected)
|
| 766 |
+
|
| 767 |
+
def test_sheet_name(self, request, read_ext, df_ref):
|
| 768 |
+
if read_ext == ".xlsb":
|
| 769 |
+
request.node.add_marker(
|
| 770 |
+
pytest.mark.xfail(
|
| 771 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 772 |
+
)
|
| 773 |
+
)
|
| 774 |
+
filename = "test1"
|
| 775 |
+
sheet_name = "Sheet1"
|
| 776 |
+
|
| 777 |
+
df1 = pd.read_excel(
|
| 778 |
+
filename + read_ext, sheet_name=sheet_name, index_col=0
|
| 779 |
+
) # doc
|
| 780 |
+
df2 = pd.read_excel(filename + read_ext, index_col=0, sheet_name=sheet_name)
|
| 781 |
+
|
| 782 |
+
tm.assert_frame_equal(df1, df_ref, check_names=False)
|
| 783 |
+
tm.assert_frame_equal(df2, df_ref, check_names=False)
|
| 784 |
+
|
| 785 |
+
def test_excel_read_buffer(self, read_ext):
|
| 786 |
+
pth = "test1" + read_ext
|
| 787 |
+
expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0)
|
| 788 |
+
with open(pth, "rb") as f:
|
| 789 |
+
actual = pd.read_excel(f, sheet_name="Sheet1", index_col=0)
|
| 790 |
+
tm.assert_frame_equal(expected, actual)
|
| 791 |
+
|
| 792 |
+
def test_bad_engine_raises(self):
|
| 793 |
+
bad_engine = "foo"
|
| 794 |
+
with pytest.raises(ValueError, match="Unknown engine: foo"):
|
| 795 |
+
pd.read_excel("", engine=bad_engine)
|
| 796 |
+
|
| 797 |
+
@pytest.mark.parametrize(
|
| 798 |
+
"sheet_name",
|
| 799 |
+
[3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],
|
| 800 |
+
)
|
| 801 |
+
def test_bad_sheetname_raises(self, read_ext, sheet_name):
|
| 802 |
+
# GH 39250
|
| 803 |
+
msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"
|
| 804 |
+
with pytest.raises(ValueError, match=msg):
|
| 805 |
+
pd.read_excel("blank" + read_ext, sheet_name=sheet_name)
|
| 806 |
+
|
| 807 |
+
def test_missing_file_raises(self, read_ext):
|
| 808 |
+
bad_file = f"foo{read_ext}"
|
| 809 |
+
# CI tests with other languages, translates to "No such file or directory"
|
| 810 |
+
match = r"(No such file or directory|没有那个文件或目录|File o directory non esistente)"
|
| 811 |
+
with pytest.raises(FileNotFoundError, match=match):
|
| 812 |
+
pd.read_excel(bad_file)
|
| 813 |
+
|
| 814 |
+
def test_corrupt_bytes_raises(self, engine):
|
| 815 |
+
bad_stream = b"foo"
|
| 816 |
+
if engine is None:
|
| 817 |
+
error = ValueError
|
| 818 |
+
msg = (
|
| 819 |
+
"Excel file format cannot be determined, you must "
|
| 820 |
+
"specify an engine manually."
|
| 821 |
+
)
|
| 822 |
+
elif engine == "xlrd":
|
| 823 |
+
from xlrd import XLRDError
|
| 824 |
+
|
| 825 |
+
error = XLRDError
|
| 826 |
+
msg = (
|
| 827 |
+
"Unsupported format, or corrupt file: Expected BOF "
|
| 828 |
+
"record; found b'foo'"
|
| 829 |
+
)
|
| 830 |
+
else:
|
| 831 |
+
error = BadZipFile
|
| 832 |
+
msg = "File is not a zip file"
|
| 833 |
+
with pytest.raises(error, match=msg):
|
| 834 |
+
pd.read_excel(bad_stream)
|
| 835 |
+
|
| 836 |
+
@pytest.mark.network
|
| 837 |
+
@tm.network(
|
| 838 |
+
url=(
|
| 839 |
+
"https://raw.githubusercontent.com/pandas-dev/pandas/main/"
|
| 840 |
+
"pandas/tests/io/data/excel/test1.xlsx"
|
| 841 |
+
),
|
| 842 |
+
check_before_test=True,
|
| 843 |
+
)
|
| 844 |
+
def test_read_from_http_url(self, read_ext):
|
| 845 |
+
url = (
|
| 846 |
+
"https://raw.githubusercontent.com/pandas-dev/pandas/main/"
|
| 847 |
+
"pandas/tests/io/data/excel/test1" + read_ext
|
| 848 |
+
)
|
| 849 |
+
url_table = pd.read_excel(url)
|
| 850 |
+
local_table = pd.read_excel("test1" + read_ext)
|
| 851 |
+
tm.assert_frame_equal(url_table, local_table)
|
| 852 |
+
|
| 853 |
+
@td.skip_if_not_us_locale
|
| 854 |
+
@pytest.mark.single_cpu
|
| 855 |
+
def test_read_from_s3_url(self, read_ext, s3_resource, s3so):
|
| 856 |
+
# Bucket "pandas-test" created in tests/io/conftest.py
|
| 857 |
+
with open("test1" + read_ext, "rb") as f:
|
| 858 |
+
s3_resource.Bucket("pandas-test").put_object(Key="test1" + read_ext, Body=f)
|
| 859 |
+
|
| 860 |
+
url = "s3://pandas-test/test1" + read_ext
|
| 861 |
+
|
| 862 |
+
url_table = pd.read_excel(url, storage_options=s3so)
|
| 863 |
+
local_table = pd.read_excel("test1" + read_ext)
|
| 864 |
+
tm.assert_frame_equal(url_table, local_table)
|
| 865 |
+
|
| 866 |
+
@pytest.mark.single_cpu
|
| 867 |
+
def test_read_from_s3_object(self, read_ext, s3_resource, s3so):
|
| 868 |
+
# GH 38788
|
| 869 |
+
# Bucket "pandas-test" created in tests/io/conftest.py
|
| 870 |
+
with open("test1" + read_ext, "rb") as f:
|
| 871 |
+
s3_resource.Bucket("pandas-test").put_object(Key="test1" + read_ext, Body=f)
|
| 872 |
+
|
| 873 |
+
import s3fs
|
| 874 |
+
|
| 875 |
+
s3 = s3fs.S3FileSystem(**s3so)
|
| 876 |
+
|
| 877 |
+
with s3.open("s3://pandas-test/test1" + read_ext) as f:
|
| 878 |
+
url_table = pd.read_excel(f)
|
| 879 |
+
|
| 880 |
+
local_table = pd.read_excel("test1" + read_ext)
|
| 881 |
+
tm.assert_frame_equal(url_table, local_table)
|
| 882 |
+
|
| 883 |
+
@pytest.mark.slow
|
| 884 |
+
def test_read_from_file_url(self, read_ext, datapath):
|
| 885 |
+
# FILE
|
| 886 |
+
localtable = os.path.join(datapath("io", "data", "excel"), "test1" + read_ext)
|
| 887 |
+
local_table = pd.read_excel(localtable)
|
| 888 |
+
|
| 889 |
+
try:
|
| 890 |
+
url_table = pd.read_excel("file://localhost/" + localtable)
|
| 891 |
+
except URLError:
|
| 892 |
+
# fails on some systems
|
| 893 |
+
platform_info = " ".join(platform.uname()).strip()
|
| 894 |
+
pytest.skip(f"failing on {platform_info}")
|
| 895 |
+
|
| 896 |
+
tm.assert_frame_equal(url_table, local_table)
|
| 897 |
+
|
| 898 |
+
def test_read_from_pathlib_path(self, read_ext):
|
| 899 |
+
# GH12655
|
| 900 |
+
str_path = "test1" + read_ext
|
| 901 |
+
expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)
|
| 902 |
+
|
| 903 |
+
path_obj = Path("test1" + read_ext)
|
| 904 |
+
actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)
|
| 905 |
+
|
| 906 |
+
tm.assert_frame_equal(expected, actual)
|
| 907 |
+
|
| 908 |
+
@td.skip_if_no("py.path")
|
| 909 |
+
def test_read_from_py_localpath(self, read_ext):
|
| 910 |
+
# GH12655
|
| 911 |
+
from py.path import local as LocalPath
|
| 912 |
+
|
| 913 |
+
str_path = os.path.join("test1" + read_ext)
|
| 914 |
+
expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)
|
| 915 |
+
|
| 916 |
+
path_obj = LocalPath().join("test1" + read_ext)
|
| 917 |
+
actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)
|
| 918 |
+
|
| 919 |
+
tm.assert_frame_equal(expected, actual)
|
| 920 |
+
|
| 921 |
+
def test_close_from_py_localpath(self, read_ext):
|
| 922 |
+
# GH31467
|
| 923 |
+
str_path = os.path.join("test1" + read_ext)
|
| 924 |
+
with open(str_path, "rb") as f:
|
| 925 |
+
x = pd.read_excel(f, sheet_name="Sheet1", index_col=0)
|
| 926 |
+
del x
|
| 927 |
+
# should not throw an exception because the passed file was closed
|
| 928 |
+
f.read()
|
| 929 |
+
|
| 930 |
+
def test_reader_seconds(self, request, engine, read_ext):
|
| 931 |
+
if engine == "pyxlsb":
|
| 932 |
+
request.node.add_marker(
|
| 933 |
+
pytest.mark.xfail(
|
| 934 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 935 |
+
)
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
# Test reading times with and without milliseconds. GH5945.
|
| 939 |
+
expected = DataFrame.from_dict(
|
| 940 |
+
{
|
| 941 |
+
"Time": [
|
| 942 |
+
time(1, 2, 3),
|
| 943 |
+
time(2, 45, 56, 100000),
|
| 944 |
+
time(4, 29, 49, 200000),
|
| 945 |
+
time(6, 13, 42, 300000),
|
| 946 |
+
time(7, 57, 35, 400000),
|
| 947 |
+
time(9, 41, 28, 500000),
|
| 948 |
+
time(11, 25, 21, 600000),
|
| 949 |
+
time(13, 9, 14, 700000),
|
| 950 |
+
time(14, 53, 7, 800000),
|
| 951 |
+
time(16, 37, 0, 900000),
|
| 952 |
+
time(18, 20, 54),
|
| 953 |
+
]
|
| 954 |
+
}
|
| 955 |
+
)
|
| 956 |
+
|
| 957 |
+
actual = pd.read_excel("times_1900" + read_ext, sheet_name="Sheet1")
|
| 958 |
+
tm.assert_frame_equal(actual, expected)
|
| 959 |
+
|
| 960 |
+
actual = pd.read_excel("times_1904" + read_ext, sheet_name="Sheet1")
|
| 961 |
+
tm.assert_frame_equal(actual, expected)
|
| 962 |
+
|
| 963 |
+
def test_read_excel_multiindex(self, request, read_ext):
|
| 964 |
+
# see gh-4679
|
| 965 |
+
if read_ext == ".xlsb":
|
| 966 |
+
request.node.add_marker(
|
| 967 |
+
pytest.mark.xfail(
|
| 968 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 969 |
+
)
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]])
|
| 973 |
+
mi_file = "testmultiindex" + read_ext
|
| 974 |
+
|
| 975 |
+
# "mi_column" sheet
|
| 976 |
+
expected = DataFrame(
|
| 977 |
+
[
|
| 978 |
+
[1, 2.5, pd.Timestamp("2015-01-01"), True],
|
| 979 |
+
[2, 3.5, pd.Timestamp("2015-01-02"), False],
|
| 980 |
+
[3, 4.5, pd.Timestamp("2015-01-03"), False],
|
| 981 |
+
[4, 5.5, pd.Timestamp("2015-01-04"), True],
|
| 982 |
+
],
|
| 983 |
+
columns=mi,
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
actual = pd.read_excel(
|
| 987 |
+
mi_file, sheet_name="mi_column", header=[0, 1], index_col=0
|
| 988 |
+
)
|
| 989 |
+
tm.assert_frame_equal(actual, expected)
|
| 990 |
+
|
| 991 |
+
# "mi_index" sheet
|
| 992 |
+
expected.index = mi
|
| 993 |
+
expected.columns = ["a", "b", "c", "d"]
|
| 994 |
+
|
| 995 |
+
actual = pd.read_excel(mi_file, sheet_name="mi_index", index_col=[0, 1])
|
| 996 |
+
tm.assert_frame_equal(actual, expected, check_names=False)
|
| 997 |
+
|
| 998 |
+
# "both" sheet
|
| 999 |
+
expected.columns = mi
|
| 1000 |
+
|
| 1001 |
+
actual = pd.read_excel(
|
| 1002 |
+
mi_file, sheet_name="both", index_col=[0, 1], header=[0, 1]
|
| 1003 |
+
)
|
| 1004 |
+
tm.assert_frame_equal(actual, expected, check_names=False)
|
| 1005 |
+
|
| 1006 |
+
# "mi_index_name" sheet
|
| 1007 |
+
expected.columns = ["a", "b", "c", "d"]
|
| 1008 |
+
expected.index = mi.set_names(["ilvl1", "ilvl2"])
|
| 1009 |
+
|
| 1010 |
+
actual = pd.read_excel(mi_file, sheet_name="mi_index_name", index_col=[0, 1])
|
| 1011 |
+
tm.assert_frame_equal(actual, expected)
|
| 1012 |
+
|
| 1013 |
+
# "mi_column_name" sheet
|
| 1014 |
+
expected.index = list(range(4))
|
| 1015 |
+
expected.columns = mi.set_names(["c1", "c2"])
|
| 1016 |
+
actual = pd.read_excel(
|
| 1017 |
+
mi_file, sheet_name="mi_column_name", header=[0, 1], index_col=0
|
| 1018 |
+
)
|
| 1019 |
+
tm.assert_frame_equal(actual, expected)
|
| 1020 |
+
|
| 1021 |
+
# see gh-11317
|
| 1022 |
+
# "name_with_int" sheet
|
| 1023 |
+
expected.columns = mi.set_levels([1, 2], level=1).set_names(["c1", "c2"])
|
| 1024 |
+
|
| 1025 |
+
actual = pd.read_excel(
|
| 1026 |
+
mi_file, sheet_name="name_with_int", index_col=0, header=[0, 1]
|
| 1027 |
+
)
|
| 1028 |
+
tm.assert_frame_equal(actual, expected)
|
| 1029 |
+
|
| 1030 |
+
# "both_name" sheet
|
| 1031 |
+
expected.columns = mi.set_names(["c1", "c2"])
|
| 1032 |
+
expected.index = mi.set_names(["ilvl1", "ilvl2"])
|
| 1033 |
+
|
| 1034 |
+
actual = pd.read_excel(
|
| 1035 |
+
mi_file, sheet_name="both_name", index_col=[0, 1], header=[0, 1]
|
| 1036 |
+
)
|
| 1037 |
+
tm.assert_frame_equal(actual, expected)
|
| 1038 |
+
|
| 1039 |
+
# "both_skiprows" sheet
|
| 1040 |
+
actual = pd.read_excel(
|
| 1041 |
+
mi_file,
|
| 1042 |
+
sheet_name="both_name_skiprows",
|
| 1043 |
+
index_col=[0, 1],
|
| 1044 |
+
header=[0, 1],
|
| 1045 |
+
skiprows=2,
|
| 1046 |
+
)
|
| 1047 |
+
tm.assert_frame_equal(actual, expected)
|
| 1048 |
+
|
| 1049 |
+
@pytest.mark.parametrize(
|
| 1050 |
+
"sheet_name,idx_lvl2",
|
| 1051 |
+
[
|
| 1052 |
+
("both_name_blank_after_mi_name", [np.nan, "b", "a", "b"]),
|
| 1053 |
+
("both_name_multiple_blanks", [np.nan] * 4),
|
| 1054 |
+
],
|
| 1055 |
+
)
|
| 1056 |
+
def test_read_excel_multiindex_blank_after_name(
|
| 1057 |
+
self, request, read_ext, sheet_name, idx_lvl2
|
| 1058 |
+
):
|
| 1059 |
+
# GH34673
|
| 1060 |
+
if read_ext == ".xlsb":
|
| 1061 |
+
request.node.add_marker(
|
| 1062 |
+
pytest.mark.xfail(
|
| 1063 |
+
reason="Sheets containing datetimes not supported by pyxlsb (GH4679"
|
| 1064 |
+
)
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
mi_file = "testmultiindex" + read_ext
|
| 1068 |
+
mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]], names=["c1", "c2"])
|
| 1069 |
+
expected = DataFrame(
|
| 1070 |
+
[
|
| 1071 |
+
[1, 2.5, pd.Timestamp("2015-01-01"), True],
|
| 1072 |
+
[2, 3.5, pd.Timestamp("2015-01-02"), False],
|
| 1073 |
+
[3, 4.5, pd.Timestamp("2015-01-03"), False],
|
| 1074 |
+
[4, 5.5, pd.Timestamp("2015-01-04"), True],
|
| 1075 |
+
],
|
| 1076 |
+
columns=mi,
|
| 1077 |
+
index=MultiIndex.from_arrays(
|
| 1078 |
+
(["foo", "foo", "bar", "bar"], idx_lvl2),
|
| 1079 |
+
names=["ilvl1", "ilvl2"],
|
| 1080 |
+
),
|
| 1081 |
+
)
|
| 1082 |
+
result = pd.read_excel(
|
| 1083 |
+
mi_file,
|
| 1084 |
+
sheet_name=sheet_name,
|
| 1085 |
+
index_col=[0, 1],
|
| 1086 |
+
header=[0, 1],
|
| 1087 |
+
)
|
| 1088 |
+
tm.assert_frame_equal(result, expected)
|
| 1089 |
+
|
| 1090 |
+
def test_read_excel_multiindex_header_only(self, read_ext):
|
| 1091 |
+
# see gh-11733.
|
| 1092 |
+
#
|
| 1093 |
+
# Don't try to parse a header name if there isn't one.
|
| 1094 |
+
mi_file = "testmultiindex" + read_ext
|
| 1095 |
+
result = pd.read_excel(mi_file, sheet_name="index_col_none", header=[0, 1])
|
| 1096 |
+
|
| 1097 |
+
exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])
|
| 1098 |
+
expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)
|
| 1099 |
+
tm.assert_frame_equal(result, expected)
|
| 1100 |
+
|
| 1101 |
+
def test_excel_old_index_format(self, read_ext):
|
| 1102 |
+
# see gh-4679
|
| 1103 |
+
filename = "test_index_name_pre17" + read_ext
|
| 1104 |
+
|
| 1105 |
+
# We detect headers to determine if index names exist, so
|
| 1106 |
+
# that "index" name in the "names" version of the data will
|
| 1107 |
+
# now be interpreted as rows that include null data.
|
| 1108 |
+
data = np.array(
|
| 1109 |
+
[
|
| 1110 |
+
[None, None, None, None, None],
|
| 1111 |
+
["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
|
| 1112 |
+
["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
|
| 1113 |
+
["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
|
| 1114 |
+
["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
|
| 1115 |
+
["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"],
|
| 1116 |
+
]
|
| 1117 |
+
)
|
| 1118 |
+
columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
|
| 1119 |
+
mi = MultiIndex(
|
| 1120 |
+
levels=[
|
| 1121 |
+
["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"],
|
| 1122 |
+
["R1", "R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"],
|
| 1123 |
+
],
|
| 1124 |
+
codes=[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]],
|
| 1125 |
+
names=[None, None],
|
| 1126 |
+
)
|
| 1127 |
+
si = Index(
|
| 1128 |
+
["R0", "R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None
|
| 1129 |
+
)
|
| 1130 |
+
|
| 1131 |
+
expected = DataFrame(data, index=si, columns=columns)
|
| 1132 |
+
|
| 1133 |
+
actual = pd.read_excel(filename, sheet_name="single_names", index_col=0)
|
| 1134 |
+
tm.assert_frame_equal(actual, expected)
|
| 1135 |
+
|
| 1136 |
+
expected.index = mi
|
| 1137 |
+
|
| 1138 |
+
actual = pd.read_excel(filename, sheet_name="multi_names", index_col=[0, 1])
|
| 1139 |
+
tm.assert_frame_equal(actual, expected)
|
| 1140 |
+
|
| 1141 |
+
# The analogous versions of the "names" version data
|
| 1142 |
+
# where there are explicitly no names for the indices.
|
| 1143 |
+
data = np.array(
|
| 1144 |
+
[
|
| 1145 |
+
["R0C0", "R0C1", "R0C2", "R0C3", "R0C4"],
|
| 1146 |
+
["R1C0", "R1C1", "R1C2", "R1C3", "R1C4"],
|
| 1147 |
+
["R2C0", "R2C1", "R2C2", "R2C3", "R2C4"],
|
| 1148 |
+
["R3C0", "R3C1", "R3C2", "R3C3", "R3C4"],
|
| 1149 |
+
["R4C0", "R4C1", "R4C2", "R4C3", "R4C4"],
|
| 1150 |
+
]
|
| 1151 |
+
)
|
| 1152 |
+
columns = ["C_l0_g0", "C_l0_g1", "C_l0_g2", "C_l0_g3", "C_l0_g4"]
|
| 1153 |
+
mi = MultiIndex(
|
| 1154 |
+
levels=[
|
| 1155 |
+
["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"],
|
| 1156 |
+
["R_l1_g0", "R_l1_g1", "R_l1_g2", "R_l1_g3", "R_l1_g4"],
|
| 1157 |
+
],
|
| 1158 |
+
codes=[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
|
| 1159 |
+
names=[None, None],
|
| 1160 |
+
)
|
| 1161 |
+
si = Index(["R_l0_g0", "R_l0_g1", "R_l0_g2", "R_l0_g3", "R_l0_g4"], name=None)
|
| 1162 |
+
|
| 1163 |
+
expected = DataFrame(data, index=si, columns=columns)
|
| 1164 |
+
|
| 1165 |
+
actual = pd.read_excel(filename, sheet_name="single_no_names", index_col=0)
|
| 1166 |
+
tm.assert_frame_equal(actual, expected)
|
| 1167 |
+
|
| 1168 |
+
expected.index = mi
|
| 1169 |
+
|
| 1170 |
+
actual = pd.read_excel(filename, sheet_name="multi_no_names", index_col=[0, 1])
|
| 1171 |
+
tm.assert_frame_equal(actual, expected, check_names=False)
|
| 1172 |
+
|
| 1173 |
+
def test_read_excel_bool_header_arg(self, read_ext):
|
| 1174 |
+
# GH 6114
|
| 1175 |
+
msg = "Passing a bool to header is invalid"
|
| 1176 |
+
for arg in [True, False]:
|
| 1177 |
+
with pytest.raises(TypeError, match=msg):
|
| 1178 |
+
pd.read_excel("test1" + read_ext, header=arg)
|
| 1179 |
+
|
| 1180 |
+
def test_read_excel_skiprows(self, request, read_ext):
|
| 1181 |
+
# GH 4903
|
| 1182 |
+
if read_ext == ".xlsb":
|
| 1183 |
+
request.node.add_marker(
|
| 1184 |
+
pytest.mark.xfail(
|
| 1185 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 1186 |
+
)
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
actual = pd.read_excel(
|
| 1190 |
+
"testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2]
|
| 1191 |
+
)
|
| 1192 |
+
expected = DataFrame(
|
| 1193 |
+
[
|
| 1194 |
+
[1, 2.5, pd.Timestamp("2015-01-01"), True],
|
| 1195 |
+
[2, 3.5, pd.Timestamp("2015-01-02"), False],
|
| 1196 |
+
[3, 4.5, pd.Timestamp("2015-01-03"), False],
|
| 1197 |
+
[4, 5.5, pd.Timestamp("2015-01-04"), True],
|
| 1198 |
+
],
|
| 1199 |
+
columns=["a", "b", "c", "d"],
|
| 1200 |
+
)
|
| 1201 |
+
tm.assert_frame_equal(actual, expected)
|
| 1202 |
+
|
| 1203 |
+
actual = pd.read_excel(
|
| 1204 |
+
"testskiprows" + read_ext,
|
| 1205 |
+
sheet_name="skiprows_list",
|
| 1206 |
+
skiprows=np.array([0, 2]),
|
| 1207 |
+
)
|
| 1208 |
+
tm.assert_frame_equal(actual, expected)
|
| 1209 |
+
|
| 1210 |
+
# GH36435
|
| 1211 |
+
actual = pd.read_excel(
|
| 1212 |
+
"testskiprows" + read_ext,
|
| 1213 |
+
sheet_name="skiprows_list",
|
| 1214 |
+
skiprows=lambda x: x in [0, 2],
|
| 1215 |
+
)
|
| 1216 |
+
tm.assert_frame_equal(actual, expected)
|
| 1217 |
+
|
| 1218 |
+
actual = pd.read_excel(
|
| 1219 |
+
"testskiprows" + read_ext,
|
| 1220 |
+
sheet_name="skiprows_list",
|
| 1221 |
+
skiprows=3,
|
| 1222 |
+
names=["a", "b", "c", "d"],
|
| 1223 |
+
)
|
| 1224 |
+
expected = DataFrame(
|
| 1225 |
+
[
|
| 1226 |
+
# [1, 2.5, pd.Timestamp("2015-01-01"), True],
|
| 1227 |
+
[2, 3.5, pd.Timestamp("2015-01-02"), False],
|
| 1228 |
+
[3, 4.5, pd.Timestamp("2015-01-03"), False],
|
| 1229 |
+
[4, 5.5, pd.Timestamp("2015-01-04"), True],
|
| 1230 |
+
],
|
| 1231 |
+
columns=["a", "b", "c", "d"],
|
| 1232 |
+
)
|
| 1233 |
+
tm.assert_frame_equal(actual, expected)
|
| 1234 |
+
|
| 1235 |
+
def test_read_excel_skiprows_callable_not_in(self, request, read_ext):
|
| 1236 |
+
# GH 4903
|
| 1237 |
+
if read_ext == ".xlsb":
|
| 1238 |
+
request.node.add_marker(
|
| 1239 |
+
pytest.mark.xfail(
|
| 1240 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 1241 |
+
)
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
actual = pd.read_excel(
|
| 1245 |
+
"testskiprows" + read_ext,
|
| 1246 |
+
sheet_name="skiprows_list",
|
| 1247 |
+
skiprows=lambda x: x not in [1, 3, 5],
|
| 1248 |
+
)
|
| 1249 |
+
expected = DataFrame(
|
| 1250 |
+
[
|
| 1251 |
+
[1, 2.5, pd.Timestamp("2015-01-01"), True],
|
| 1252 |
+
# [2, 3.5, pd.Timestamp("2015-01-02"), False],
|
| 1253 |
+
[3, 4.5, pd.Timestamp("2015-01-03"), False],
|
| 1254 |
+
# [4, 5.5, pd.Timestamp("2015-01-04"), True],
|
| 1255 |
+
],
|
| 1256 |
+
columns=["a", "b", "c", "d"],
|
| 1257 |
+
)
|
| 1258 |
+
tm.assert_frame_equal(actual, expected)
|
| 1259 |
+
|
| 1260 |
+
def test_read_excel_nrows(self, read_ext):
|
| 1261 |
+
# GH 16645
|
| 1262 |
+
num_rows_to_pull = 5
|
| 1263 |
+
actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull)
|
| 1264 |
+
expected = pd.read_excel("test1" + read_ext)
|
| 1265 |
+
expected = expected[:num_rows_to_pull]
|
| 1266 |
+
tm.assert_frame_equal(actual, expected)
|
| 1267 |
+
|
| 1268 |
+
def test_read_excel_nrows_greater_than_nrows_in_file(self, read_ext):
|
| 1269 |
+
# GH 16645
|
| 1270 |
+
expected = pd.read_excel("test1" + read_ext)
|
| 1271 |
+
num_records_in_file = len(expected)
|
| 1272 |
+
num_rows_to_pull = num_records_in_file + 10
|
| 1273 |
+
actual = pd.read_excel("test1" + read_ext, nrows=num_rows_to_pull)
|
| 1274 |
+
tm.assert_frame_equal(actual, expected)
|
| 1275 |
+
|
| 1276 |
+
def test_read_excel_nrows_non_integer_parameter(self, read_ext):
|
| 1277 |
+
# GH 16645
|
| 1278 |
+
msg = "'nrows' must be an integer >=0"
|
| 1279 |
+
with pytest.raises(ValueError, match=msg):
|
| 1280 |
+
pd.read_excel("test1" + read_ext, nrows="5")
|
| 1281 |
+
|
| 1282 |
+
@pytest.mark.parametrize(
|
| 1283 |
+
"filename,sheet_name,header,index_col,skiprows",
|
| 1284 |
+
[
|
| 1285 |
+
("testmultiindex", "mi_column", [0, 1], 0, None),
|
| 1286 |
+
("testmultiindex", "mi_index", None, [0, 1], None),
|
| 1287 |
+
("testmultiindex", "both", [0, 1], [0, 1], None),
|
| 1288 |
+
("testmultiindex", "mi_column_name", [0, 1], 0, None),
|
| 1289 |
+
("testskiprows", "skiprows_list", None, None, [0, 2]),
|
| 1290 |
+
("testskiprows", "skiprows_list", None, None, lambda x: x in (0, 2)),
|
| 1291 |
+
],
|
| 1292 |
+
)
|
| 1293 |
+
def test_read_excel_nrows_params(
|
| 1294 |
+
self, read_ext, filename, sheet_name, header, index_col, skiprows
|
| 1295 |
+
):
|
| 1296 |
+
"""
|
| 1297 |
+
For various parameters, we should get the same result whether we
|
| 1298 |
+
limit the rows during load (nrows=3) or after (df.iloc[:3]).
|
| 1299 |
+
"""
|
| 1300 |
+
# GH 46894
|
| 1301 |
+
expected = pd.read_excel(
|
| 1302 |
+
filename + read_ext,
|
| 1303 |
+
sheet_name=sheet_name,
|
| 1304 |
+
header=header,
|
| 1305 |
+
index_col=index_col,
|
| 1306 |
+
skiprows=skiprows,
|
| 1307 |
+
).iloc[:3]
|
| 1308 |
+
actual = pd.read_excel(
|
| 1309 |
+
filename + read_ext,
|
| 1310 |
+
sheet_name=sheet_name,
|
| 1311 |
+
header=header,
|
| 1312 |
+
index_col=index_col,
|
| 1313 |
+
skiprows=skiprows,
|
| 1314 |
+
nrows=3,
|
| 1315 |
+
)
|
| 1316 |
+
tm.assert_frame_equal(actual, expected)
|
| 1317 |
+
|
| 1318 |
+
def test_deprecated_kwargs(self, read_ext):
|
| 1319 |
+
with pytest.raises(TypeError, match="but 3 positional arguments"):
|
| 1320 |
+
pd.read_excel("test1" + read_ext, "Sheet1", 0)
|
| 1321 |
+
|
| 1322 |
+
def test_no_header_with_list_index_col(self, read_ext):
|
| 1323 |
+
# GH 31783
|
| 1324 |
+
file_name = "testmultiindex" + read_ext
|
| 1325 |
+
data = [("B", "B"), ("key", "val"), (3, 4), (3, 4)]
|
| 1326 |
+
idx = MultiIndex.from_tuples(
|
| 1327 |
+
[("A", "A"), ("key", "val"), (1, 2), (1, 2)], names=(0, 1)
|
| 1328 |
+
)
|
| 1329 |
+
expected = DataFrame(data, index=idx, columns=(2, 3))
|
| 1330 |
+
result = pd.read_excel(
|
| 1331 |
+
file_name, sheet_name="index_col_none", index_col=[0, 1], header=None
|
| 1332 |
+
)
|
| 1333 |
+
tm.assert_frame_equal(expected, result)
|
| 1334 |
+
|
| 1335 |
+
def test_one_col_noskip_blank_line(self, read_ext):
|
| 1336 |
+
# GH 39808
|
| 1337 |
+
file_name = "one_col_blank_line" + read_ext
|
| 1338 |
+
data = [0.5, np.nan, 1, 2]
|
| 1339 |
+
expected = DataFrame(data, columns=["numbers"])
|
| 1340 |
+
result = pd.read_excel(file_name)
|
| 1341 |
+
tm.assert_frame_equal(result, expected)
|
| 1342 |
+
|
| 1343 |
+
def test_multiheader_two_blank_lines(self, read_ext):
|
| 1344 |
+
# GH 40442
|
| 1345 |
+
file_name = "testmultiindex" + read_ext
|
| 1346 |
+
columns = MultiIndex.from_tuples([("a", "A"), ("b", "B")])
|
| 1347 |
+
data = [[np.nan, np.nan], [np.nan, np.nan], [1, 3], [2, 4]]
|
| 1348 |
+
expected = DataFrame(data, columns=columns)
|
| 1349 |
+
result = pd.read_excel(
|
| 1350 |
+
file_name, sheet_name="mi_column_empty_rows", header=[0, 1]
|
| 1351 |
+
)
|
| 1352 |
+
tm.assert_frame_equal(result, expected)
|
| 1353 |
+
|
| 1354 |
+
def test_trailing_blanks(self, read_ext):
|
| 1355 |
+
"""
|
| 1356 |
+
Sheets can contain blank cells with no data. Some of our readers
|
| 1357 |
+
were including those cells, creating many empty rows and columns
|
| 1358 |
+
"""
|
| 1359 |
+
file_name = "trailing_blanks" + read_ext
|
| 1360 |
+
result = pd.read_excel(file_name)
|
| 1361 |
+
assert result.shape == (3, 3)
|
| 1362 |
+
|
| 1363 |
+
def test_ignore_chartsheets_by_str(self, request, engine, read_ext):
|
| 1364 |
+
# GH 41448
|
| 1365 |
+
if engine == "odf":
|
| 1366 |
+
pytest.skip("chartsheets do not exist in the ODF format")
|
| 1367 |
+
if engine == "pyxlsb":
|
| 1368 |
+
request.node.add_marker(
|
| 1369 |
+
pytest.mark.xfail(
|
| 1370 |
+
reason="pyxlsb can't distinguish chartsheets from worksheets"
|
| 1371 |
+
)
|
| 1372 |
+
)
|
| 1373 |
+
with pytest.raises(ValueError, match="Worksheet named 'Chart1' not found"):
|
| 1374 |
+
pd.read_excel("chartsheet" + read_ext, sheet_name="Chart1")
|
| 1375 |
+
|
| 1376 |
+
def test_ignore_chartsheets_by_int(self, request, engine, read_ext):
|
| 1377 |
+
# GH 41448
|
| 1378 |
+
if engine == "odf":
|
| 1379 |
+
pytest.skip("chartsheets do not exist in the ODF format")
|
| 1380 |
+
if engine == "pyxlsb":
|
| 1381 |
+
request.node.add_marker(
|
| 1382 |
+
pytest.mark.xfail(
|
| 1383 |
+
reason="pyxlsb can't distinguish chartsheets from worksheets"
|
| 1384 |
+
)
|
| 1385 |
+
)
|
| 1386 |
+
with pytest.raises(
|
| 1387 |
+
ValueError, match="Worksheet index 1 is invalid, 1 worksheets found"
|
| 1388 |
+
):
|
| 1389 |
+
pd.read_excel("chartsheet" + read_ext, sheet_name=1)
|
| 1390 |
+
|
| 1391 |
+
def test_euro_decimal_format(self, read_ext):
|
| 1392 |
+
# copied from read_csv
|
| 1393 |
+
result = pd.read_excel("test_decimal" + read_ext, decimal=",", skiprows=1)
|
| 1394 |
+
expected = DataFrame(
|
| 1395 |
+
[
|
| 1396 |
+
[1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819],
|
| 1397 |
+
[2, 121.12, 14897.76, "DEF", "uyt", 0.377320872],
|
| 1398 |
+
[3, 878.158, 108013.434, "GHI", "rez", 2.735694704],
|
| 1399 |
+
],
|
| 1400 |
+
columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"],
|
| 1401 |
+
)
|
| 1402 |
+
tm.assert_frame_equal(result, expected)
|
| 1403 |
+
|
| 1404 |
+
|
| 1405 |
+
class TestExcelFileRead:
|
| 1406 |
+
@pytest.fixture(autouse=True)
|
| 1407 |
+
def cd_and_set_engine(self, engine, datapath, monkeypatch):
|
| 1408 |
+
"""
|
| 1409 |
+
Change directory and set engine for ExcelFile objects.
|
| 1410 |
+
"""
|
| 1411 |
+
func = partial(pd.ExcelFile, engine=engine)
|
| 1412 |
+
monkeypatch.chdir(datapath("io", "data", "excel"))
|
| 1413 |
+
monkeypatch.setattr(pd, "ExcelFile", func)
|
| 1414 |
+
|
| 1415 |
+
def test_engine_used(self, read_ext, engine):
|
| 1416 |
+
expected_defaults = {
|
| 1417 |
+
"xlsx": "openpyxl",
|
| 1418 |
+
"xlsm": "openpyxl",
|
| 1419 |
+
"xlsb": "pyxlsb",
|
| 1420 |
+
"xls": "xlrd",
|
| 1421 |
+
"ods": "odf",
|
| 1422 |
+
}
|
| 1423 |
+
|
| 1424 |
+
with pd.ExcelFile("test1" + read_ext) as excel:
|
| 1425 |
+
result = excel.engine
|
| 1426 |
+
|
| 1427 |
+
if engine is not None:
|
| 1428 |
+
expected = engine
|
| 1429 |
+
else:
|
| 1430 |
+
expected = expected_defaults[read_ext[1:]]
|
| 1431 |
+
assert result == expected
|
| 1432 |
+
|
| 1433 |
+
def test_excel_passes_na(self, read_ext):
|
| 1434 |
+
with pd.ExcelFile("test4" + read_ext) as excel:
|
| 1435 |
+
parsed = pd.read_excel(
|
| 1436 |
+
excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]
|
| 1437 |
+
)
|
| 1438 |
+
expected = DataFrame(
|
| 1439 |
+
[["NA"], [1], ["NA"], [np.nan], ["rabbit"]], columns=["Test"]
|
| 1440 |
+
)
|
| 1441 |
+
tm.assert_frame_equal(parsed, expected)
|
| 1442 |
+
|
| 1443 |
+
with pd.ExcelFile("test4" + read_ext) as excel:
|
| 1444 |
+
parsed = pd.read_excel(
|
| 1445 |
+
excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]
|
| 1446 |
+
)
|
| 1447 |
+
expected = DataFrame(
|
| 1448 |
+
[[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]
|
| 1449 |
+
)
|
| 1450 |
+
tm.assert_frame_equal(parsed, expected)
|
| 1451 |
+
|
| 1452 |
+
# 13967
|
| 1453 |
+
with pd.ExcelFile("test5" + read_ext) as excel:
|
| 1454 |
+
parsed = pd.read_excel(
|
| 1455 |
+
excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]
|
| 1456 |
+
)
|
| 1457 |
+
expected = DataFrame(
|
| 1458 |
+
[["1.#QNAN"], [1], ["nan"], [np.nan], ["rabbit"]], columns=["Test"]
|
| 1459 |
+
)
|
| 1460 |
+
tm.assert_frame_equal(parsed, expected)
|
| 1461 |
+
|
| 1462 |
+
with pd.ExcelFile("test5" + read_ext) as excel:
|
| 1463 |
+
parsed = pd.read_excel(
|
| 1464 |
+
excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]
|
| 1465 |
+
)
|
| 1466 |
+
expected = DataFrame(
|
| 1467 |
+
[[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]
|
| 1468 |
+
)
|
| 1469 |
+
tm.assert_frame_equal(parsed, expected)
|
| 1470 |
+
|
| 1471 |
+
@pytest.mark.parametrize("na_filter", [None, True, False])
|
| 1472 |
+
def test_excel_passes_na_filter(self, read_ext, na_filter):
|
| 1473 |
+
# gh-25453
|
| 1474 |
+
kwargs = {}
|
| 1475 |
+
|
| 1476 |
+
if na_filter is not None:
|
| 1477 |
+
kwargs["na_filter"] = na_filter
|
| 1478 |
+
|
| 1479 |
+
with pd.ExcelFile("test5" + read_ext) as excel:
|
| 1480 |
+
parsed = pd.read_excel(
|
| 1481 |
+
excel,
|
| 1482 |
+
sheet_name="Sheet1",
|
| 1483 |
+
keep_default_na=True,
|
| 1484 |
+
na_values=["apple"],
|
| 1485 |
+
**kwargs,
|
| 1486 |
+
)
|
| 1487 |
+
|
| 1488 |
+
if na_filter is False:
|
| 1489 |
+
expected = [["1.#QNAN"], [1], ["nan"], ["apple"], ["rabbit"]]
|
| 1490 |
+
else:
|
| 1491 |
+
expected = [[np.nan], [1], [np.nan], [np.nan], ["rabbit"]]
|
| 1492 |
+
|
| 1493 |
+
expected = DataFrame(expected, columns=["Test"])
|
| 1494 |
+
tm.assert_frame_equal(parsed, expected)
|
| 1495 |
+
|
| 1496 |
+
def test_excel_table_sheet_by_index(self, request, read_ext, df_ref):
|
| 1497 |
+
if read_ext == ".xlsb":
|
| 1498 |
+
request.node.add_marker(
|
| 1499 |
+
pytest.mark.xfail(
|
| 1500 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 1501 |
+
)
|
| 1502 |
+
)
|
| 1503 |
+
|
| 1504 |
+
with pd.ExcelFile("test1" + read_ext) as excel:
|
| 1505 |
+
df1 = pd.read_excel(excel, sheet_name=0, index_col=0)
|
| 1506 |
+
df2 = pd.read_excel(excel, sheet_name=1, skiprows=[1], index_col=0)
|
| 1507 |
+
tm.assert_frame_equal(df1, df_ref, check_names=False)
|
| 1508 |
+
tm.assert_frame_equal(df2, df_ref, check_names=False)
|
| 1509 |
+
|
| 1510 |
+
with pd.ExcelFile("test1" + read_ext) as excel:
|
| 1511 |
+
df1 = excel.parse(0, index_col=0)
|
| 1512 |
+
df2 = excel.parse(1, skiprows=[1], index_col=0)
|
| 1513 |
+
tm.assert_frame_equal(df1, df_ref, check_names=False)
|
| 1514 |
+
tm.assert_frame_equal(df2, df_ref, check_names=False)
|
| 1515 |
+
|
| 1516 |
+
with pd.ExcelFile("test1" + read_ext) as excel:
|
| 1517 |
+
df3 = pd.read_excel(excel, sheet_name=0, index_col=0, skipfooter=1)
|
| 1518 |
+
tm.assert_frame_equal(df3, df1.iloc[:-1])
|
| 1519 |
+
|
| 1520 |
+
with pd.ExcelFile("test1" + read_ext) as excel:
|
| 1521 |
+
df3 = excel.parse(0, index_col=0, skipfooter=1)
|
| 1522 |
+
|
| 1523 |
+
tm.assert_frame_equal(df3, df1.iloc[:-1])
|
| 1524 |
+
|
| 1525 |
+
def test_sheet_name(self, request, read_ext, df_ref):
|
| 1526 |
+
if read_ext == ".xlsb":
|
| 1527 |
+
request.node.add_marker(
|
| 1528 |
+
pytest.mark.xfail(
|
| 1529 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 1530 |
+
)
|
| 1531 |
+
)
|
| 1532 |
+
|
| 1533 |
+
filename = "test1"
|
| 1534 |
+
sheet_name = "Sheet1"
|
| 1535 |
+
|
| 1536 |
+
with pd.ExcelFile(filename + read_ext) as excel:
|
| 1537 |
+
df1_parse = excel.parse(sheet_name=sheet_name, index_col=0) # doc
|
| 1538 |
+
|
| 1539 |
+
with pd.ExcelFile(filename + read_ext) as excel:
|
| 1540 |
+
df2_parse = excel.parse(index_col=0, sheet_name=sheet_name)
|
| 1541 |
+
|
| 1542 |
+
tm.assert_frame_equal(df1_parse, df_ref, check_names=False)
|
| 1543 |
+
tm.assert_frame_equal(df2_parse, df_ref, check_names=False)
|
| 1544 |
+
|
| 1545 |
+
@pytest.mark.parametrize(
|
| 1546 |
+
"sheet_name",
|
| 1547 |
+
[3, [0, 3], [3, 0], "Sheet4", ["Sheet1", "Sheet4"], ["Sheet4", "Sheet1"]],
|
| 1548 |
+
)
|
| 1549 |
+
def test_bad_sheetname_raises(self, read_ext, sheet_name):
|
| 1550 |
+
# GH 39250
|
| 1551 |
+
msg = "Worksheet index 3 is invalid|Worksheet named 'Sheet4' not found"
|
| 1552 |
+
with pytest.raises(ValueError, match=msg):
|
| 1553 |
+
with pd.ExcelFile("blank" + read_ext) as excel:
|
| 1554 |
+
excel.parse(sheet_name=sheet_name)
|
| 1555 |
+
|
| 1556 |
+
def test_excel_read_buffer(self, engine, read_ext):
|
| 1557 |
+
pth = "test1" + read_ext
|
| 1558 |
+
expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine)
|
| 1559 |
+
|
| 1560 |
+
with open(pth, "rb") as f:
|
| 1561 |
+
with pd.ExcelFile(f) as xls:
|
| 1562 |
+
actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0)
|
| 1563 |
+
|
| 1564 |
+
tm.assert_frame_equal(expected, actual)
|
| 1565 |
+
|
| 1566 |
+
def test_reader_closes_file(self, engine, read_ext):
|
| 1567 |
+
with open("test1" + read_ext, "rb") as f:
|
| 1568 |
+
with pd.ExcelFile(f) as xlsx:
|
| 1569 |
+
# parses okay
|
| 1570 |
+
pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine)
|
| 1571 |
+
|
| 1572 |
+
assert f.closed
|
| 1573 |
+
|
| 1574 |
+
def test_conflicting_excel_engines(self, read_ext):
|
| 1575 |
+
# GH 26566
|
| 1576 |
+
msg = "Engine should not be specified when passing an ExcelFile"
|
| 1577 |
+
|
| 1578 |
+
with pd.ExcelFile("test1" + read_ext) as xl:
|
| 1579 |
+
with pytest.raises(ValueError, match=msg):
|
| 1580 |
+
pd.read_excel(xl, engine="foo")
|
| 1581 |
+
|
| 1582 |
+
def test_excel_read_binary(self, engine, read_ext):
|
| 1583 |
+
# GH 15914
|
| 1584 |
+
expected = pd.read_excel("test1" + read_ext, engine=engine)
|
| 1585 |
+
|
| 1586 |
+
with open("test1" + read_ext, "rb") as f:
|
| 1587 |
+
data = f.read()
|
| 1588 |
+
|
| 1589 |
+
actual = pd.read_excel(data, engine=engine)
|
| 1590 |
+
tm.assert_frame_equal(expected, actual)
|
| 1591 |
+
|
| 1592 |
+
def test_excel_read_binary_via_read_excel(self, read_ext, engine):
|
| 1593 |
+
# GH 38424
|
| 1594 |
+
with open("test1" + read_ext, "rb") as f:
|
| 1595 |
+
result = pd.read_excel(f)
|
| 1596 |
+
expected = pd.read_excel("test1" + read_ext, engine=engine)
|
| 1597 |
+
tm.assert_frame_equal(result, expected)
|
| 1598 |
+
|
| 1599 |
+
def test_read_excel_header_index_out_of_range(self, engine):
|
| 1600 |
+
# GH#43143
|
| 1601 |
+
with open("df_header_oob.xlsx", "rb") as f:
|
| 1602 |
+
with pytest.raises(ValueError, match="exceeds maximum"):
|
| 1603 |
+
pd.read_excel(f, header=[0, 1])
|
| 1604 |
+
|
| 1605 |
+
@pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"])
|
| 1606 |
+
def test_header_with_index_col(self, filename):
|
| 1607 |
+
# GH 33476
|
| 1608 |
+
idx = Index(["Z"], name="I2")
|
| 1609 |
+
cols = MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"])
|
| 1610 |
+
expected = DataFrame([[1, 3]], index=idx, columns=cols, dtype="int64")
|
| 1611 |
+
result = pd.read_excel(
|
| 1612 |
+
filename, sheet_name="Sheet1", index_col=0, header=[0, 1]
|
| 1613 |
+
)
|
| 1614 |
+
tm.assert_frame_equal(expected, result)
|
| 1615 |
+
|
| 1616 |
+
def test_read_datetime_multiindex(self, request, engine, read_ext):
|
| 1617 |
+
# GH 34748
|
| 1618 |
+
if engine == "pyxlsb":
|
| 1619 |
+
request.node.add_marker(
|
| 1620 |
+
pytest.mark.xfail(
|
| 1621 |
+
reason="Sheets containing datetimes not supported by pyxlsb"
|
| 1622 |
+
)
|
| 1623 |
+
)
|
| 1624 |
+
|
| 1625 |
+
f = "test_datetime_mi" + read_ext
|
| 1626 |
+
with pd.ExcelFile(f) as excel:
|
| 1627 |
+
actual = pd.read_excel(excel, header=[0, 1], index_col=0, engine=engine)
|
| 1628 |
+
expected_column_index = MultiIndex.from_tuples(
|
| 1629 |
+
[(pd.to_datetime("02/29/2020"), pd.to_datetime("03/01/2020"))],
|
| 1630 |
+
names=[
|
| 1631 |
+
pd.to_datetime("02/29/2020").to_pydatetime(),
|
| 1632 |
+
pd.to_datetime("03/01/2020").to_pydatetime(),
|
| 1633 |
+
],
|
| 1634 |
+
)
|
| 1635 |
+
expected = DataFrame([], index=[], columns=expected_column_index)
|
| 1636 |
+
|
| 1637 |
+
tm.assert_frame_equal(expected, actual)
|
| 1638 |
+
|
| 1639 |
+
def test_engine_invalid_option(self, read_ext):
|
| 1640 |
+
# read_ext includes the '.' hence the weird formatting
|
| 1641 |
+
with pytest.raises(ValueError, match="Value must be one of *"):
|
| 1642 |
+
with pd.option_context(f"io.excel{read_ext}.reader", "abc"):
|
| 1643 |
+
pass
|
| 1644 |
+
|
| 1645 |
+
def test_ignore_chartsheets(self, request, engine, read_ext):
|
| 1646 |
+
# GH 41448
|
| 1647 |
+
if engine == "odf":
|
| 1648 |
+
pytest.skip("chartsheets do not exist in the ODF format")
|
| 1649 |
+
if engine == "pyxlsb":
|
| 1650 |
+
request.node.add_marker(
|
| 1651 |
+
pytest.mark.xfail(
|
| 1652 |
+
reason="pyxlsb can't distinguish chartsheets from worksheets"
|
| 1653 |
+
)
|
| 1654 |
+
)
|
| 1655 |
+
with pd.ExcelFile("chartsheet" + read_ext) as excel:
|
| 1656 |
+
assert excel.sheet_names == ["Sheet1"]
|
| 1657 |
+
|
| 1658 |
+
def test_corrupt_files_closed(self, engine, read_ext):
|
| 1659 |
+
# GH41778
|
| 1660 |
+
errors = (BadZipFile,)
|
| 1661 |
+
if engine is None:
|
| 1662 |
+
pytest.skip(f"Invalid test for engine={engine}")
|
| 1663 |
+
elif engine == "xlrd":
|
| 1664 |
+
import xlrd
|
| 1665 |
+
|
| 1666 |
+
errors = (BadZipFile, xlrd.biffh.XLRDError)
|
| 1667 |
+
|
| 1668 |
+
with tm.ensure_clean(f"corrupt{read_ext}") as file:
|
| 1669 |
+
Path(file).write_text("corrupt")
|
| 1670 |
+
with tm.assert_produces_warning(False):
|
| 1671 |
+
try:
|
| 1672 |
+
pd.ExcelFile(file, engine=engine)
|
| 1673 |
+
except errors:
|
| 1674 |
+
pass
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/excel/test_writers.py
ADDED
|
@@ -0,0 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pytest
|
| 13 |
+
|
| 14 |
+
import pandas.util._test_decorators as td
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
from pandas import (
|
| 18 |
+
DataFrame,
|
| 19 |
+
Index,
|
| 20 |
+
MultiIndex,
|
| 21 |
+
option_context,
|
| 22 |
+
)
|
| 23 |
+
import pandas._testing as tm
|
| 24 |
+
|
| 25 |
+
from pandas.io.excel import (
|
| 26 |
+
ExcelFile,
|
| 27 |
+
ExcelWriter,
|
| 28 |
+
_OpenpyxlWriter,
|
| 29 |
+
_XlsxWriter,
|
| 30 |
+
register_writer,
|
| 31 |
+
)
|
| 32 |
+
from pandas.io.excel._util import _writers
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.fixture
|
| 36 |
+
def path(ext):
|
| 37 |
+
"""
|
| 38 |
+
Fixture to open file for use in each test case.
|
| 39 |
+
"""
|
| 40 |
+
with tm.ensure_clean(ext) as file_path:
|
| 41 |
+
yield file_path
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.fixture
|
| 45 |
+
def set_engine(engine, ext):
|
| 46 |
+
"""
|
| 47 |
+
Fixture to set engine for use in each test case.
|
| 48 |
+
|
| 49 |
+
Rather than requiring `engine=...` to be provided explicitly as an
|
| 50 |
+
argument in each test, this fixture sets a global option to dictate
|
| 51 |
+
which engine should be used to write Excel files. After executing
|
| 52 |
+
the test it rolls back said change to the global option.
|
| 53 |
+
"""
|
| 54 |
+
option_name = f"io.excel.{ext.strip('.')}.writer"
|
| 55 |
+
with option_context(option_name, engine):
|
| 56 |
+
yield
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize(
|
| 60 |
+
"ext",
|
| 61 |
+
[
|
| 62 |
+
pytest.param(".xlsx", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),
|
| 63 |
+
pytest.param(".xlsm", marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")]),
|
| 64 |
+
pytest.param(
|
| 65 |
+
".xlsx", marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")]
|
| 66 |
+
),
|
| 67 |
+
pytest.param(".ods", marks=td.skip_if_no("odf")),
|
| 68 |
+
],
|
| 69 |
+
)
|
| 70 |
+
class TestRoundTrip:
|
| 71 |
+
@pytest.mark.parametrize(
|
| 72 |
+
"header,expected",
|
| 73 |
+
[(None, DataFrame([np.nan] * 4)), (0, DataFrame({"Unnamed: 0": [np.nan] * 3}))],
|
| 74 |
+
)
|
| 75 |
+
def test_read_one_empty_col_no_header(self, ext, header, expected):
|
| 76 |
+
# xref gh-12292
|
| 77 |
+
filename = "no_header"
|
| 78 |
+
df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])
|
| 79 |
+
|
| 80 |
+
with tm.ensure_clean(ext) as path:
|
| 81 |
+
df.to_excel(path, filename, index=False, header=False)
|
| 82 |
+
result = pd.read_excel(
|
| 83 |
+
path, sheet_name=filename, usecols=[0], header=header
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
tm.assert_frame_equal(result, expected)
|
| 87 |
+
|
| 88 |
+
@pytest.mark.parametrize(
|
| 89 |
+
"header,expected",
|
| 90 |
+
[(None, DataFrame([0] + [np.nan] * 4)), (0, DataFrame([np.nan] * 4))],
|
| 91 |
+
)
|
| 92 |
+
def test_read_one_empty_col_with_header(self, ext, header, expected):
|
| 93 |
+
filename = "with_header"
|
| 94 |
+
df = DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]])
|
| 95 |
+
|
| 96 |
+
with tm.ensure_clean(ext) as path:
|
| 97 |
+
df.to_excel(path, "with_header", index=False, header=True)
|
| 98 |
+
result = pd.read_excel(
|
| 99 |
+
path, sheet_name=filename, usecols=[0], header=header
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
tm.assert_frame_equal(result, expected)
|
| 103 |
+
|
| 104 |
+
def test_set_column_names_in_parameter(self, ext):
|
| 105 |
+
# GH 12870 : pass down column names associated with
|
| 106 |
+
# keyword argument names
|
| 107 |
+
refdf = DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"])
|
| 108 |
+
|
| 109 |
+
with tm.ensure_clean(ext) as pth:
|
| 110 |
+
with ExcelWriter(pth) as writer:
|
| 111 |
+
refdf.to_excel(writer, "Data_no_head", header=False, index=False)
|
| 112 |
+
refdf.to_excel(writer, "Data_with_head", index=False)
|
| 113 |
+
|
| 114 |
+
refdf.columns = ["A", "B"]
|
| 115 |
+
|
| 116 |
+
with ExcelFile(pth) as reader:
|
| 117 |
+
xlsdf_no_head = pd.read_excel(
|
| 118 |
+
reader, sheet_name="Data_no_head", header=None, names=["A", "B"]
|
| 119 |
+
)
|
| 120 |
+
xlsdf_with_head = pd.read_excel(
|
| 121 |
+
reader,
|
| 122 |
+
sheet_name="Data_with_head",
|
| 123 |
+
index_col=None,
|
| 124 |
+
names=["A", "B"],
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
tm.assert_frame_equal(xlsdf_no_head, refdf)
|
| 128 |
+
tm.assert_frame_equal(xlsdf_with_head, refdf)
|
| 129 |
+
|
| 130 |
+
def test_creating_and_reading_multiple_sheets(self, ext):
|
| 131 |
+
# see gh-9450
|
| 132 |
+
#
|
| 133 |
+
# Test reading multiple sheets, from a runtime
|
| 134 |
+
# created Excel file with multiple sheets.
|
| 135 |
+
def tdf(col_sheet_name):
|
| 136 |
+
d, i = [11, 22, 33], [1, 2, 3]
|
| 137 |
+
return DataFrame(d, i, columns=[col_sheet_name])
|
| 138 |
+
|
| 139 |
+
sheets = ["AAA", "BBB", "CCC"]
|
| 140 |
+
|
| 141 |
+
dfs = [tdf(s) for s in sheets]
|
| 142 |
+
dfs = dict(zip(sheets, dfs))
|
| 143 |
+
|
| 144 |
+
with tm.ensure_clean(ext) as pth:
|
| 145 |
+
with ExcelWriter(pth) as ew:
|
| 146 |
+
for sheetname, df in dfs.items():
|
| 147 |
+
df.to_excel(ew, sheetname)
|
| 148 |
+
|
| 149 |
+
dfs_returned = pd.read_excel(pth, sheet_name=sheets, index_col=0)
|
| 150 |
+
|
| 151 |
+
for s in sheets:
|
| 152 |
+
tm.assert_frame_equal(dfs[s], dfs_returned[s])
|
| 153 |
+
|
| 154 |
+
def test_read_excel_multiindex_empty_level(self, ext):
|
| 155 |
+
# see gh-12453
|
| 156 |
+
with tm.ensure_clean(ext) as path:
|
| 157 |
+
df = DataFrame(
|
| 158 |
+
{
|
| 159 |
+
("One", "x"): {0: 1},
|
| 160 |
+
("Two", "X"): {0: 3},
|
| 161 |
+
("Two", "Y"): {0: 7},
|
| 162 |
+
("Zero", ""): {0: 0},
|
| 163 |
+
}
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
expected = DataFrame(
|
| 167 |
+
{
|
| 168 |
+
("One", "x"): {0: 1},
|
| 169 |
+
("Two", "X"): {0: 3},
|
| 170 |
+
("Two", "Y"): {0: 7},
|
| 171 |
+
("Zero", "Unnamed: 4_level_1"): {0: 0},
|
| 172 |
+
}
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
df.to_excel(path)
|
| 176 |
+
actual = pd.read_excel(path, header=[0, 1], index_col=0)
|
| 177 |
+
tm.assert_frame_equal(actual, expected)
|
| 178 |
+
|
| 179 |
+
df = DataFrame(
|
| 180 |
+
{
|
| 181 |
+
("Beg", ""): {0: 0},
|
| 182 |
+
("Middle", "x"): {0: 1},
|
| 183 |
+
("Tail", "X"): {0: 3},
|
| 184 |
+
("Tail", "Y"): {0: 7},
|
| 185 |
+
}
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
expected = DataFrame(
|
| 189 |
+
{
|
| 190 |
+
("Beg", "Unnamed: 1_level_1"): {0: 0},
|
| 191 |
+
("Middle", "x"): {0: 1},
|
| 192 |
+
("Tail", "X"): {0: 3},
|
| 193 |
+
("Tail", "Y"): {0: 7},
|
| 194 |
+
}
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
df.to_excel(path)
|
| 198 |
+
actual = pd.read_excel(path, header=[0, 1], index_col=0)
|
| 199 |
+
tm.assert_frame_equal(actual, expected)
|
| 200 |
+
|
| 201 |
+
@pytest.mark.parametrize("c_idx_names", [True, False])
|
| 202 |
+
@pytest.mark.parametrize("r_idx_names", [True, False])
|
| 203 |
+
@pytest.mark.parametrize("c_idx_levels", [1, 3])
|
| 204 |
+
@pytest.mark.parametrize("r_idx_levels", [1, 3])
|
| 205 |
+
def test_excel_multindex_roundtrip(
|
| 206 |
+
self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels, request
|
| 207 |
+
):
|
| 208 |
+
# see gh-4679
|
| 209 |
+
with tm.ensure_clean(ext) as pth:
|
| 210 |
+
if (c_idx_levels == 1 and c_idx_names) and not (
|
| 211 |
+
r_idx_levels == 3 and not r_idx_names
|
| 212 |
+
):
|
| 213 |
+
mark = pytest.mark.xfail(
|
| 214 |
+
reason="Column index name cannot be serialized unless "
|
| 215 |
+
"it's a MultiIndex"
|
| 216 |
+
)
|
| 217 |
+
request.node.add_marker(mark)
|
| 218 |
+
|
| 219 |
+
# Empty name case current read in as
|
| 220 |
+
# unnamed levels, not Nones.
|
| 221 |
+
check_names = r_idx_names or r_idx_levels <= 1
|
| 222 |
+
|
| 223 |
+
df = tm.makeCustomDataframe(
|
| 224 |
+
5, 5, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels
|
| 225 |
+
)
|
| 226 |
+
df.to_excel(pth)
|
| 227 |
+
|
| 228 |
+
act = pd.read_excel(
|
| 229 |
+
pth,
|
| 230 |
+
index_col=list(range(r_idx_levels)),
|
| 231 |
+
header=list(range(c_idx_levels)),
|
| 232 |
+
)
|
| 233 |
+
tm.assert_frame_equal(df, act, check_names=check_names)
|
| 234 |
+
|
| 235 |
+
df.iloc[0, :] = np.nan
|
| 236 |
+
df.to_excel(pth)
|
| 237 |
+
|
| 238 |
+
act = pd.read_excel(
|
| 239 |
+
pth,
|
| 240 |
+
index_col=list(range(r_idx_levels)),
|
| 241 |
+
header=list(range(c_idx_levels)),
|
| 242 |
+
)
|
| 243 |
+
tm.assert_frame_equal(df, act, check_names=check_names)
|
| 244 |
+
|
| 245 |
+
df.iloc[-1, :] = np.nan
|
| 246 |
+
df.to_excel(pth)
|
| 247 |
+
act = pd.read_excel(
|
| 248 |
+
pth,
|
| 249 |
+
index_col=list(range(r_idx_levels)),
|
| 250 |
+
header=list(range(c_idx_levels)),
|
| 251 |
+
)
|
| 252 |
+
tm.assert_frame_equal(df, act, check_names=check_names)
|
| 253 |
+
|
| 254 |
+
def test_read_excel_parse_dates(self, ext):
|
| 255 |
+
# see gh-11544, gh-12051
|
| 256 |
+
df = DataFrame(
|
| 257 |
+
{"col": [1, 2, 3], "date_strings": pd.date_range("2012-01-01", periods=3)}
|
| 258 |
+
)
|
| 259 |
+
df2 = df.copy()
|
| 260 |
+
df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y")
|
| 261 |
+
|
| 262 |
+
with tm.ensure_clean(ext) as pth:
|
| 263 |
+
df2.to_excel(pth)
|
| 264 |
+
|
| 265 |
+
res = pd.read_excel(pth, index_col=0)
|
| 266 |
+
tm.assert_frame_equal(df2, res)
|
| 267 |
+
|
| 268 |
+
res = pd.read_excel(pth, parse_dates=["date_strings"], index_col=0)
|
| 269 |
+
tm.assert_frame_equal(df, res)
|
| 270 |
+
|
| 271 |
+
date_parser = lambda x: datetime.strptime(x, "%m/%d/%Y")
|
| 272 |
+
with tm.assert_produces_warning(
|
| 273 |
+
FutureWarning, match="use 'date_format' instead"
|
| 274 |
+
):
|
| 275 |
+
res = pd.read_excel(
|
| 276 |
+
pth,
|
| 277 |
+
parse_dates=["date_strings"],
|
| 278 |
+
date_parser=date_parser,
|
| 279 |
+
index_col=0,
|
| 280 |
+
)
|
| 281 |
+
tm.assert_frame_equal(df, res)
|
| 282 |
+
res = pd.read_excel(
|
| 283 |
+
pth, parse_dates=["date_strings"], date_format="%m/%d/%Y", index_col=0
|
| 284 |
+
)
|
| 285 |
+
tm.assert_frame_equal(df, res)
|
| 286 |
+
|
| 287 |
+
def test_multiindex_interval_datetimes(self, ext):
|
| 288 |
+
# GH 30986
|
| 289 |
+
midx = MultiIndex.from_arrays(
|
| 290 |
+
[
|
| 291 |
+
range(4),
|
| 292 |
+
pd.interval_range(
|
| 293 |
+
start=pd.Timestamp("2020-01-01"), periods=4, freq="6M"
|
| 294 |
+
),
|
| 295 |
+
]
|
| 296 |
+
)
|
| 297 |
+
df = DataFrame(range(4), index=midx)
|
| 298 |
+
with tm.ensure_clean(ext) as pth:
|
| 299 |
+
df.to_excel(pth)
|
| 300 |
+
result = pd.read_excel(pth, index_col=[0, 1])
|
| 301 |
+
expected = DataFrame(
|
| 302 |
+
range(4),
|
| 303 |
+
MultiIndex.from_arrays(
|
| 304 |
+
[
|
| 305 |
+
range(4),
|
| 306 |
+
[
|
| 307 |
+
"(2020-01-31, 2020-07-31]",
|
| 308 |
+
"(2020-07-31, 2021-01-31]",
|
| 309 |
+
"(2021-01-31, 2021-07-31]",
|
| 310 |
+
"(2021-07-31, 2022-01-31]",
|
| 311 |
+
],
|
| 312 |
+
]
|
| 313 |
+
),
|
| 314 |
+
)
|
| 315 |
+
tm.assert_frame_equal(result, expected)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@pytest.mark.parametrize(
|
| 319 |
+
"engine,ext",
|
| 320 |
+
[
|
| 321 |
+
pytest.param(
|
| 322 |
+
"openpyxl",
|
| 323 |
+
".xlsx",
|
| 324 |
+
marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],
|
| 325 |
+
),
|
| 326 |
+
pytest.param(
|
| 327 |
+
"openpyxl",
|
| 328 |
+
".xlsm",
|
| 329 |
+
marks=[td.skip_if_no("openpyxl"), td.skip_if_no("xlrd")],
|
| 330 |
+
),
|
| 331 |
+
pytest.param(
|
| 332 |
+
"xlsxwriter",
|
| 333 |
+
".xlsx",
|
| 334 |
+
marks=[td.skip_if_no("xlsxwriter"), td.skip_if_no("xlrd")],
|
| 335 |
+
),
|
| 336 |
+
pytest.param("odf", ".ods", marks=td.skip_if_no("odf")),
|
| 337 |
+
],
|
| 338 |
+
)
|
| 339 |
+
@pytest.mark.usefixtures("set_engine")
|
| 340 |
+
class TestExcelWriter:
|
| 341 |
+
def test_excel_sheet_size(self, path):
|
| 342 |
+
# GH 26080
|
| 343 |
+
breaking_row_count = 2**20 + 1
|
| 344 |
+
breaking_col_count = 2**14 + 1
|
| 345 |
+
# purposely using two arrays to prevent memory issues while testing
|
| 346 |
+
row_arr = np.zeros(shape=(breaking_row_count, 1))
|
| 347 |
+
col_arr = np.zeros(shape=(1, breaking_col_count))
|
| 348 |
+
row_df = DataFrame(row_arr)
|
| 349 |
+
col_df = DataFrame(col_arr)
|
| 350 |
+
|
| 351 |
+
msg = "sheet is too large"
|
| 352 |
+
with pytest.raises(ValueError, match=msg):
|
| 353 |
+
row_df.to_excel(path)
|
| 354 |
+
|
| 355 |
+
with pytest.raises(ValueError, match=msg):
|
| 356 |
+
col_df.to_excel(path)
|
| 357 |
+
|
| 358 |
+
def test_excel_sheet_by_name_raise(self, path):
|
| 359 |
+
gt = DataFrame(np.random.randn(10, 2))
|
| 360 |
+
gt.to_excel(path)
|
| 361 |
+
|
| 362 |
+
with ExcelFile(path) as xl:
|
| 363 |
+
df = pd.read_excel(xl, sheet_name=0, index_col=0)
|
| 364 |
+
|
| 365 |
+
tm.assert_frame_equal(gt, df)
|
| 366 |
+
|
| 367 |
+
msg = "Worksheet named '0' not found"
|
| 368 |
+
with pytest.raises(ValueError, match=msg):
|
| 369 |
+
pd.read_excel(xl, "0")
|
| 370 |
+
|
| 371 |
+
def test_excel_writer_context_manager(self, frame, path):
|
| 372 |
+
with ExcelWriter(path) as writer:
|
| 373 |
+
frame.to_excel(writer, "Data1")
|
| 374 |
+
frame2 = frame.copy()
|
| 375 |
+
frame2.columns = frame.columns[::-1]
|
| 376 |
+
frame2.to_excel(writer, "Data2")
|
| 377 |
+
|
| 378 |
+
with ExcelFile(path) as reader:
|
| 379 |
+
found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0)
|
| 380 |
+
found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0)
|
| 381 |
+
|
| 382 |
+
tm.assert_frame_equal(found_df, frame)
|
| 383 |
+
tm.assert_frame_equal(found_df2, frame2)
|
| 384 |
+
|
| 385 |
+
def test_roundtrip(self, frame, path):
|
| 386 |
+
frame = frame.copy()
|
| 387 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 388 |
+
|
| 389 |
+
frame.to_excel(path, "test1")
|
| 390 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 391 |
+
frame.to_excel(path, "test1", header=False)
|
| 392 |
+
frame.to_excel(path, "test1", index=False)
|
| 393 |
+
|
| 394 |
+
# test roundtrip
|
| 395 |
+
frame.to_excel(path, "test1")
|
| 396 |
+
recons = pd.read_excel(path, sheet_name="test1", index_col=0)
|
| 397 |
+
tm.assert_frame_equal(frame, recons)
|
| 398 |
+
|
| 399 |
+
frame.to_excel(path, "test1", index=False)
|
| 400 |
+
recons = pd.read_excel(path, sheet_name="test1", index_col=None)
|
| 401 |
+
recons.index = frame.index
|
| 402 |
+
tm.assert_frame_equal(frame, recons)
|
| 403 |
+
|
| 404 |
+
frame.to_excel(path, "test1", na_rep="NA")
|
| 405 |
+
recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"])
|
| 406 |
+
tm.assert_frame_equal(frame, recons)
|
| 407 |
+
|
| 408 |
+
# GH 3611
|
| 409 |
+
frame.to_excel(path, "test1", na_rep="88")
|
| 410 |
+
recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"])
|
| 411 |
+
tm.assert_frame_equal(frame, recons)
|
| 412 |
+
|
| 413 |
+
frame.to_excel(path, "test1", na_rep="88")
|
| 414 |
+
recons = pd.read_excel(
|
| 415 |
+
path, sheet_name="test1", index_col=0, na_values=[88, 88.0]
|
| 416 |
+
)
|
| 417 |
+
tm.assert_frame_equal(frame, recons)
|
| 418 |
+
|
| 419 |
+
# GH 6573
|
| 420 |
+
frame.to_excel(path, "Sheet1")
|
| 421 |
+
recons = pd.read_excel(path, index_col=0)
|
| 422 |
+
tm.assert_frame_equal(frame, recons)
|
| 423 |
+
|
| 424 |
+
frame.to_excel(path, "0")
|
| 425 |
+
recons = pd.read_excel(path, index_col=0)
|
| 426 |
+
tm.assert_frame_equal(frame, recons)
|
| 427 |
+
|
| 428 |
+
# GH 8825 Pandas Series should provide to_excel method
|
| 429 |
+
s = frame["A"]
|
| 430 |
+
s.to_excel(path)
|
| 431 |
+
recons = pd.read_excel(path, index_col=0)
|
| 432 |
+
tm.assert_frame_equal(s.to_frame(), recons)
|
| 433 |
+
|
| 434 |
+
def test_mixed(self, frame, path):
|
| 435 |
+
mixed_frame = frame.copy()
|
| 436 |
+
mixed_frame["foo"] = "bar"
|
| 437 |
+
|
| 438 |
+
mixed_frame.to_excel(path, "test1")
|
| 439 |
+
with ExcelFile(path) as reader:
|
| 440 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 441 |
+
tm.assert_frame_equal(mixed_frame, recons)
|
| 442 |
+
|
| 443 |
+
def test_ts_frame(self, tsframe, path):
|
| 444 |
+
df = tsframe
|
| 445 |
+
|
| 446 |
+
# freq doesn't round-trip
|
| 447 |
+
index = pd.DatetimeIndex(np.asarray(df.index), freq=None)
|
| 448 |
+
df.index = index
|
| 449 |
+
|
| 450 |
+
df.to_excel(path, "test1")
|
| 451 |
+
with ExcelFile(path) as reader:
|
| 452 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 453 |
+
tm.assert_frame_equal(df, recons)
|
| 454 |
+
|
| 455 |
+
def test_basics_with_nan(self, frame, path):
|
| 456 |
+
frame = frame.copy()
|
| 457 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 458 |
+
frame.to_excel(path, "test1")
|
| 459 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 460 |
+
frame.to_excel(path, "test1", header=False)
|
| 461 |
+
frame.to_excel(path, "test1", index=False)
|
| 462 |
+
|
| 463 |
+
@pytest.mark.parametrize("np_type", [np.int8, np.int16, np.int32, np.int64])
|
| 464 |
+
def test_int_types(self, np_type, path):
|
| 465 |
+
# Test np.int values read come back as int
|
| 466 |
+
# (rather than float which is Excel's format).
|
| 467 |
+
df = DataFrame(np.random.randint(-10, 10, size=(10, 2)), dtype=np_type)
|
| 468 |
+
df.to_excel(path, "test1")
|
| 469 |
+
|
| 470 |
+
with ExcelFile(path) as reader:
|
| 471 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 472 |
+
|
| 473 |
+
int_frame = df.astype(np.int64)
|
| 474 |
+
tm.assert_frame_equal(int_frame, recons)
|
| 475 |
+
|
| 476 |
+
recons2 = pd.read_excel(path, sheet_name="test1", index_col=0)
|
| 477 |
+
tm.assert_frame_equal(int_frame, recons2)
|
| 478 |
+
|
| 479 |
+
@pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64])
|
| 480 |
+
def test_float_types(self, np_type, path):
|
| 481 |
+
# Test np.float values read come back as float.
|
| 482 |
+
df = DataFrame(np.random.random_sample(10), dtype=np_type)
|
| 483 |
+
df.to_excel(path, "test1")
|
| 484 |
+
|
| 485 |
+
with ExcelFile(path) as reader:
|
| 486 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
|
| 487 |
+
np_type
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
tm.assert_frame_equal(df, recons)
|
| 491 |
+
|
| 492 |
+
def test_bool_types(self, path):
|
| 493 |
+
# Test np.bool_ values read come back as float.
|
| 494 |
+
df = DataFrame([1, 0, True, False], dtype=np.bool_)
|
| 495 |
+
df.to_excel(path, "test1")
|
| 496 |
+
|
| 497 |
+
with ExcelFile(path) as reader:
|
| 498 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
|
| 499 |
+
np.bool_
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
tm.assert_frame_equal(df, recons)
|
| 503 |
+
|
| 504 |
+
def test_inf_roundtrip(self, path):
|
| 505 |
+
df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
|
| 506 |
+
df.to_excel(path, "test1")
|
| 507 |
+
|
| 508 |
+
with ExcelFile(path) as reader:
|
| 509 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 510 |
+
|
| 511 |
+
tm.assert_frame_equal(df, recons)
|
| 512 |
+
|
| 513 |
+
def test_sheets(self, frame, tsframe, path):
|
| 514 |
+
# freq doesn't round-trip
|
| 515 |
+
index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
|
| 516 |
+
tsframe.index = index
|
| 517 |
+
|
| 518 |
+
frame = frame.copy()
|
| 519 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 520 |
+
|
| 521 |
+
frame.to_excel(path, "test1")
|
| 522 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 523 |
+
frame.to_excel(path, "test1", header=False)
|
| 524 |
+
frame.to_excel(path, "test1", index=False)
|
| 525 |
+
|
| 526 |
+
# Test writing to separate sheets
|
| 527 |
+
with ExcelWriter(path) as writer:
|
| 528 |
+
frame.to_excel(writer, "test1")
|
| 529 |
+
tsframe.to_excel(writer, "test2")
|
| 530 |
+
with ExcelFile(path) as reader:
|
| 531 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 532 |
+
tm.assert_frame_equal(frame, recons)
|
| 533 |
+
recons = pd.read_excel(reader, sheet_name="test2", index_col=0)
|
| 534 |
+
tm.assert_frame_equal(tsframe, recons)
|
| 535 |
+
assert 2 == len(reader.sheet_names)
|
| 536 |
+
assert "test1" == reader.sheet_names[0]
|
| 537 |
+
assert "test2" == reader.sheet_names[1]
|
| 538 |
+
|
| 539 |
+
def test_colaliases(self, frame, path):
|
| 540 |
+
frame = frame.copy()
|
| 541 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 542 |
+
|
| 543 |
+
frame.to_excel(path, "test1")
|
| 544 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 545 |
+
frame.to_excel(path, "test1", header=False)
|
| 546 |
+
frame.to_excel(path, "test1", index=False)
|
| 547 |
+
|
| 548 |
+
# column aliases
|
| 549 |
+
col_aliases = Index(["AA", "X", "Y", "Z"])
|
| 550 |
+
frame.to_excel(path, "test1", header=col_aliases)
|
| 551 |
+
with ExcelFile(path) as reader:
|
| 552 |
+
rs = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 553 |
+
xp = frame.copy()
|
| 554 |
+
xp.columns = col_aliases
|
| 555 |
+
tm.assert_frame_equal(xp, rs)
|
| 556 |
+
|
| 557 |
+
def test_roundtrip_indexlabels(self, merge_cells, frame, path):
|
| 558 |
+
frame = frame.copy()
|
| 559 |
+
frame.iloc[:5, frame.columns.get_loc("A")] = np.nan
|
| 560 |
+
|
| 561 |
+
frame.to_excel(path, "test1")
|
| 562 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 563 |
+
frame.to_excel(path, "test1", header=False)
|
| 564 |
+
frame.to_excel(path, "test1", index=False)
|
| 565 |
+
|
| 566 |
+
# test index_label
|
| 567 |
+
df = DataFrame(np.random.randn(10, 2)) >= 0
|
| 568 |
+
df.to_excel(path, "test1", index_label=["test"], merge_cells=merge_cells)
|
| 569 |
+
with ExcelFile(path) as reader:
|
| 570 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
|
| 571 |
+
np.int64
|
| 572 |
+
)
|
| 573 |
+
df.index.names = ["test"]
|
| 574 |
+
assert df.index.names == recons.index.names
|
| 575 |
+
|
| 576 |
+
df = DataFrame(np.random.randn(10, 2)) >= 0
|
| 577 |
+
df.to_excel(
|
| 578 |
+
path,
|
| 579 |
+
"test1",
|
| 580 |
+
index_label=["test", "dummy", "dummy2"],
|
| 581 |
+
merge_cells=merge_cells,
|
| 582 |
+
)
|
| 583 |
+
with ExcelFile(path) as reader:
|
| 584 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
|
| 585 |
+
np.int64
|
| 586 |
+
)
|
| 587 |
+
df.index.names = ["test"]
|
| 588 |
+
assert df.index.names == recons.index.names
|
| 589 |
+
|
| 590 |
+
df = DataFrame(np.random.randn(10, 2)) >= 0
|
| 591 |
+
df.to_excel(path, "test1", index_label="test", merge_cells=merge_cells)
|
| 592 |
+
with ExcelFile(path) as reader:
|
| 593 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
|
| 594 |
+
np.int64
|
| 595 |
+
)
|
| 596 |
+
df.index.names = ["test"]
|
| 597 |
+
tm.assert_frame_equal(df, recons.astype(bool))
|
| 598 |
+
|
| 599 |
+
frame.to_excel(
|
| 600 |
+
path,
|
| 601 |
+
"test1",
|
| 602 |
+
columns=["A", "B", "C", "D"],
|
| 603 |
+
index=False,
|
| 604 |
+
merge_cells=merge_cells,
|
| 605 |
+
)
|
| 606 |
+
# take 'A' and 'B' as indexes (same row as cols 'C', 'D')
|
| 607 |
+
df = frame.copy()
|
| 608 |
+
df = df.set_index(["A", "B"])
|
| 609 |
+
|
| 610 |
+
with ExcelFile(path) as reader:
|
| 611 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
|
| 612 |
+
tm.assert_frame_equal(df, recons)
|
| 613 |
+
|
| 614 |
+
def test_excel_roundtrip_indexname(self, merge_cells, path):
|
| 615 |
+
df = DataFrame(np.random.randn(10, 4))
|
| 616 |
+
df.index.name = "foo"
|
| 617 |
+
|
| 618 |
+
df.to_excel(path, merge_cells=merge_cells)
|
| 619 |
+
|
| 620 |
+
with ExcelFile(path) as xf:
|
| 621 |
+
result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0)
|
| 622 |
+
|
| 623 |
+
tm.assert_frame_equal(result, df)
|
| 624 |
+
assert result.index.name == "foo"
|
| 625 |
+
|
| 626 |
+
def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path):
|
| 627 |
+
# datetime.date, not sure what to test here exactly
|
| 628 |
+
|
| 629 |
+
# freq does not round-trip
|
| 630 |
+
index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
|
| 631 |
+
tsframe.index = index
|
| 632 |
+
|
| 633 |
+
tsf = tsframe.copy()
|
| 634 |
+
|
| 635 |
+
tsf.index = [x.date() for x in tsframe.index]
|
| 636 |
+
tsf.to_excel(path, "test1", merge_cells=merge_cells)
|
| 637 |
+
|
| 638 |
+
with ExcelFile(path) as reader:
|
| 639 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 640 |
+
|
| 641 |
+
tm.assert_frame_equal(tsframe, recons)
|
| 642 |
+
|
| 643 |
+
def test_excel_date_datetime_format(self, ext, path):
|
| 644 |
+
# see gh-4133
|
| 645 |
+
#
|
| 646 |
+
# Excel output format strings
|
| 647 |
+
df = DataFrame(
|
| 648 |
+
[
|
| 649 |
+
[date(2014, 1, 31), date(1999, 9, 24)],
|
| 650 |
+
[datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
|
| 651 |
+
],
|
| 652 |
+
index=["DATE", "DATETIME"],
|
| 653 |
+
columns=["X", "Y"],
|
| 654 |
+
)
|
| 655 |
+
df_expected = DataFrame(
|
| 656 |
+
[
|
| 657 |
+
[datetime(2014, 1, 31), datetime(1999, 9, 24)],
|
| 658 |
+
[datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
|
| 659 |
+
],
|
| 660 |
+
index=["DATE", "DATETIME"],
|
| 661 |
+
columns=["X", "Y"],
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
with tm.ensure_clean(ext) as filename2:
|
| 665 |
+
with ExcelWriter(path) as writer1:
|
| 666 |
+
df.to_excel(writer1, "test1")
|
| 667 |
+
|
| 668 |
+
with ExcelWriter(
|
| 669 |
+
filename2,
|
| 670 |
+
date_format="DD.MM.YYYY",
|
| 671 |
+
datetime_format="DD.MM.YYYY HH-MM-SS",
|
| 672 |
+
) as writer2:
|
| 673 |
+
df.to_excel(writer2, "test1")
|
| 674 |
+
|
| 675 |
+
with ExcelFile(path) as reader1:
|
| 676 |
+
rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0)
|
| 677 |
+
|
| 678 |
+
with ExcelFile(filename2) as reader2:
|
| 679 |
+
rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0)
|
| 680 |
+
|
| 681 |
+
tm.assert_frame_equal(rs1, rs2)
|
| 682 |
+
|
| 683 |
+
# Since the reader returns a datetime object for dates,
|
| 684 |
+
# we need to use df_expected to check the result.
|
| 685 |
+
tm.assert_frame_equal(rs2, df_expected)
|
| 686 |
+
|
| 687 |
+
def test_to_excel_interval_no_labels(self, path):
|
| 688 |
+
# see gh-19242
|
| 689 |
+
#
|
| 690 |
+
# Test writing Interval without labels.
|
| 691 |
+
df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64)
|
| 692 |
+
expected = df.copy()
|
| 693 |
+
|
| 694 |
+
df["new"] = pd.cut(df[0], 10)
|
| 695 |
+
expected["new"] = pd.cut(expected[0], 10).astype(str)
|
| 696 |
+
|
| 697 |
+
df.to_excel(path, "test1")
|
| 698 |
+
with ExcelFile(path) as reader:
|
| 699 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 700 |
+
tm.assert_frame_equal(expected, recons)
|
| 701 |
+
|
| 702 |
+
def test_to_excel_interval_labels(self, path):
|
| 703 |
+
# see gh-19242
|
| 704 |
+
#
|
| 705 |
+
# Test writing Interval with labels.
|
| 706 |
+
df = DataFrame(np.random.randint(-10, 10, size=(20, 1)), dtype=np.int64)
|
| 707 |
+
expected = df.copy()
|
| 708 |
+
intervals = pd.cut(
|
| 709 |
+
df[0], 10, labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
|
| 710 |
+
)
|
| 711 |
+
df["new"] = intervals
|
| 712 |
+
expected["new"] = pd.Series(list(intervals))
|
| 713 |
+
|
| 714 |
+
df.to_excel(path, "test1")
|
| 715 |
+
with ExcelFile(path) as reader:
|
| 716 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 717 |
+
tm.assert_frame_equal(expected, recons)
|
| 718 |
+
|
| 719 |
+
def test_to_excel_timedelta(self, path):
|
| 720 |
+
# see gh-19242, gh-9155
|
| 721 |
+
#
|
| 722 |
+
# Test writing timedelta to xls.
|
| 723 |
+
df = DataFrame(
|
| 724 |
+
np.random.randint(-10, 10, size=(20, 1)), columns=["A"], dtype=np.int64
|
| 725 |
+
)
|
| 726 |
+
expected = df.copy()
|
| 727 |
+
|
| 728 |
+
df["new"] = df["A"].apply(lambda x: timedelta(seconds=x))
|
| 729 |
+
expected["new"] = expected["A"].apply(
|
| 730 |
+
lambda x: timedelta(seconds=x).total_seconds() / 86400
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
df.to_excel(path, "test1")
|
| 734 |
+
with ExcelFile(path) as reader:
|
| 735 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 736 |
+
tm.assert_frame_equal(expected, recons)
|
| 737 |
+
|
| 738 |
+
def test_to_excel_periodindex(self, tsframe, path):
|
| 739 |
+
xp = tsframe.resample("M", kind="period").mean()
|
| 740 |
+
|
| 741 |
+
xp.to_excel(path, "sht1")
|
| 742 |
+
|
| 743 |
+
with ExcelFile(path) as reader:
|
| 744 |
+
rs = pd.read_excel(reader, sheet_name="sht1", index_col=0)
|
| 745 |
+
tm.assert_frame_equal(xp, rs.to_period("M"))
|
| 746 |
+
|
| 747 |
+
def test_to_excel_multiindex(self, merge_cells, frame, path):
|
| 748 |
+
arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1)
|
| 749 |
+
new_index = MultiIndex.from_arrays(arrays, names=["first", "second"])
|
| 750 |
+
frame.index = new_index
|
| 751 |
+
|
| 752 |
+
frame.to_excel(path, "test1", header=False)
|
| 753 |
+
frame.to_excel(path, "test1", columns=["A", "B"])
|
| 754 |
+
|
| 755 |
+
# round trip
|
| 756 |
+
frame.to_excel(path, "test1", merge_cells=merge_cells)
|
| 757 |
+
with ExcelFile(path) as reader:
|
| 758 |
+
df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
|
| 759 |
+
tm.assert_frame_equal(frame, df)
|
| 760 |
+
|
| 761 |
+
# GH13511
|
| 762 |
+
def test_to_excel_multiindex_nan_label(self, merge_cells, path):
|
| 763 |
+
df = DataFrame({"A": [None, 2, 3], "B": [10, 20, 30], "C": np.random.sample(3)})
|
| 764 |
+
df = df.set_index(["A", "B"])
|
| 765 |
+
|
| 766 |
+
df.to_excel(path, merge_cells=merge_cells)
|
| 767 |
+
df1 = pd.read_excel(path, index_col=[0, 1])
|
| 768 |
+
tm.assert_frame_equal(df, df1)
|
| 769 |
+
|
| 770 |
+
# Test for Issue 11328. If column indices are integers, make
|
| 771 |
+
# sure they are handled correctly for either setting of
|
| 772 |
+
# merge_cells
|
| 773 |
+
def test_to_excel_multiindex_cols(self, merge_cells, frame, path):
|
| 774 |
+
arrays = np.arange(len(frame.index) * 2, dtype=np.int64).reshape(2, -1)
|
| 775 |
+
new_index = MultiIndex.from_arrays(arrays, names=["first", "second"])
|
| 776 |
+
frame.index = new_index
|
| 777 |
+
|
| 778 |
+
new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2), (50, 1), (50, 2)])
|
| 779 |
+
frame.columns = new_cols_index
|
| 780 |
+
header = [0, 1]
|
| 781 |
+
if not merge_cells:
|
| 782 |
+
header = 0
|
| 783 |
+
|
| 784 |
+
# round trip
|
| 785 |
+
frame.to_excel(path, "test1", merge_cells=merge_cells)
|
| 786 |
+
with ExcelFile(path) as reader:
|
| 787 |
+
df = pd.read_excel(
|
| 788 |
+
reader, sheet_name="test1", header=header, index_col=[0, 1]
|
| 789 |
+
)
|
| 790 |
+
if not merge_cells:
|
| 791 |
+
fm = frame.columns.format(sparsify=False, adjoin=False, names=False)
|
| 792 |
+
frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
|
| 793 |
+
tm.assert_frame_equal(frame, df)
|
| 794 |
+
|
| 795 |
+
def test_to_excel_multiindex_dates(self, merge_cells, tsframe, path):
|
| 796 |
+
# try multiindex with dates
|
| 797 |
+
new_index = [tsframe.index, np.arange(len(tsframe.index), dtype=np.int64)]
|
| 798 |
+
tsframe.index = MultiIndex.from_arrays(new_index)
|
| 799 |
+
|
| 800 |
+
tsframe.index.names = ["time", "foo"]
|
| 801 |
+
tsframe.to_excel(path, "test1", merge_cells=merge_cells)
|
| 802 |
+
with ExcelFile(path) as reader:
|
| 803 |
+
recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
|
| 804 |
+
|
| 805 |
+
tm.assert_frame_equal(tsframe, recons)
|
| 806 |
+
assert recons.index.names == ("time", "foo")
|
| 807 |
+
|
| 808 |
+
def test_to_excel_multiindex_no_write_index(self, path):
|
| 809 |
+
# Test writing and re-reading a MI without the index. GH 5616.
|
| 810 |
+
|
| 811 |
+
# Initial non-MI frame.
|
| 812 |
+
frame1 = DataFrame({"a": [10, 20], "b": [30, 40], "c": [50, 60]})
|
| 813 |
+
|
| 814 |
+
# Add a MI.
|
| 815 |
+
frame2 = frame1.copy()
|
| 816 |
+
multi_index = MultiIndex.from_tuples([(70, 80), (90, 100)])
|
| 817 |
+
frame2.index = multi_index
|
| 818 |
+
|
| 819 |
+
# Write out to Excel without the index.
|
| 820 |
+
frame2.to_excel(path, "test1", index=False)
|
| 821 |
+
|
| 822 |
+
# Read it back in.
|
| 823 |
+
with ExcelFile(path) as reader:
|
| 824 |
+
frame3 = pd.read_excel(reader, sheet_name="test1")
|
| 825 |
+
|
| 826 |
+
# Test that it is the same as the initial frame.
|
| 827 |
+
tm.assert_frame_equal(frame1, frame3)
|
| 828 |
+
|
| 829 |
+
def test_to_excel_empty_multiindex(self, path):
|
| 830 |
+
# GH 19543.
|
| 831 |
+
expected = DataFrame([], columns=[0, 1, 2])
|
| 832 |
+
|
| 833 |
+
df = DataFrame([], index=MultiIndex.from_tuples([], names=[0, 1]), columns=[2])
|
| 834 |
+
df.to_excel(path, "test1")
|
| 835 |
+
|
| 836 |
+
with ExcelFile(path) as reader:
|
| 837 |
+
result = pd.read_excel(reader, sheet_name="test1")
|
| 838 |
+
tm.assert_frame_equal(
|
| 839 |
+
result, expected, check_index_type=False, check_dtype=False
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
def test_to_excel_float_format(self, path):
|
| 843 |
+
df = DataFrame(
|
| 844 |
+
[[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
|
| 845 |
+
index=["A", "B"],
|
| 846 |
+
columns=["X", "Y", "Z"],
|
| 847 |
+
)
|
| 848 |
+
df.to_excel(path, "test1", float_format="%.2f")
|
| 849 |
+
|
| 850 |
+
with ExcelFile(path) as reader:
|
| 851 |
+
result = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 852 |
+
|
| 853 |
+
expected = DataFrame(
|
| 854 |
+
[[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],
|
| 855 |
+
index=["A", "B"],
|
| 856 |
+
columns=["X", "Y", "Z"],
|
| 857 |
+
)
|
| 858 |
+
tm.assert_frame_equal(result, expected)
|
| 859 |
+
|
| 860 |
+
def test_to_excel_output_encoding(self, ext):
|
| 861 |
+
# Avoid mixed inferred_type.
|
| 862 |
+
df = DataFrame(
|
| 863 |
+
[["\u0192", "\u0193", "\u0194"], ["\u0195", "\u0196", "\u0197"]],
|
| 864 |
+
index=["A\u0192", "B"],
|
| 865 |
+
columns=["X\u0193", "Y", "Z"],
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
|
| 869 |
+
df.to_excel(filename, sheet_name="TestSheet")
|
| 870 |
+
result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0)
|
| 871 |
+
tm.assert_frame_equal(result, df)
|
| 872 |
+
|
| 873 |
+
def test_to_excel_unicode_filename(self, ext):
|
| 874 |
+
with tm.ensure_clean("\u0192u." + ext) as filename:
|
| 875 |
+
try:
|
| 876 |
+
with open(filename, "wb"):
|
| 877 |
+
pass
|
| 878 |
+
except UnicodeEncodeError:
|
| 879 |
+
pytest.skip("No unicode file names on this system")
|
| 880 |
+
|
| 881 |
+
df = DataFrame(
|
| 882 |
+
[[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
|
| 883 |
+
index=["A", "B"],
|
| 884 |
+
columns=["X", "Y", "Z"],
|
| 885 |
+
)
|
| 886 |
+
df.to_excel(filename, "test1", float_format="%.2f")
|
| 887 |
+
|
| 888 |
+
with ExcelFile(filename) as reader:
|
| 889 |
+
result = pd.read_excel(reader, sheet_name="test1", index_col=0)
|
| 890 |
+
|
| 891 |
+
expected = DataFrame(
|
| 892 |
+
[[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],
|
| 893 |
+
index=["A", "B"],
|
| 894 |
+
columns=["X", "Y", "Z"],
|
| 895 |
+
)
|
| 896 |
+
tm.assert_frame_equal(result, expected)
|
| 897 |
+
|
| 898 |
+
@pytest.mark.parametrize("use_headers", [True, False])
|
| 899 |
+
@pytest.mark.parametrize("r_idx_nlevels", [1, 2, 3])
|
| 900 |
+
@pytest.mark.parametrize("c_idx_nlevels", [1, 2, 3])
|
| 901 |
+
def test_excel_010_hemstring(
|
| 902 |
+
self, merge_cells, c_idx_nlevels, r_idx_nlevels, use_headers, path
|
| 903 |
+
):
|
| 904 |
+
def roundtrip(data, header=True, parser_hdr=0, index=True):
|
| 905 |
+
data.to_excel(path, header=header, merge_cells=merge_cells, index=index)
|
| 906 |
+
|
| 907 |
+
with ExcelFile(path) as xf:
|
| 908 |
+
return pd.read_excel(
|
| 909 |
+
xf, sheet_name=xf.sheet_names[0], header=parser_hdr
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
# Basic test.
|
| 913 |
+
parser_header = 0 if use_headers else None
|
| 914 |
+
res = roundtrip(DataFrame([0]), use_headers, parser_header)
|
| 915 |
+
|
| 916 |
+
assert res.shape == (1, 2)
|
| 917 |
+
assert res.iloc[0, 0] is not np.nan
|
| 918 |
+
|
| 919 |
+
# More complex tests with multi-index.
|
| 920 |
+
nrows = 5
|
| 921 |
+
ncols = 3
|
| 922 |
+
|
| 923 |
+
# ensure limited functionality in 0.10
|
| 924 |
+
# override of gh-2370 until sorted out in 0.11
|
| 925 |
+
|
| 926 |
+
df = tm.makeCustomDataframe(
|
| 927 |
+
nrows, ncols, r_idx_nlevels=r_idx_nlevels, c_idx_nlevels=c_idx_nlevels
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
# This if will be removed once multi-column Excel writing
|
| 931 |
+
# is implemented. For now fixing gh-9794.
|
| 932 |
+
if c_idx_nlevels > 1:
|
| 933 |
+
msg = (
|
| 934 |
+
"Writing to Excel with MultiIndex columns and no index "
|
| 935 |
+
"\\('index'=False\\) is not yet implemented."
|
| 936 |
+
)
|
| 937 |
+
with pytest.raises(NotImplementedError, match=msg):
|
| 938 |
+
roundtrip(df, use_headers, index=False)
|
| 939 |
+
else:
|
| 940 |
+
res = roundtrip(df, use_headers)
|
| 941 |
+
|
| 942 |
+
if use_headers:
|
| 943 |
+
assert res.shape == (nrows, ncols + r_idx_nlevels)
|
| 944 |
+
else:
|
| 945 |
+
# First row taken as columns.
|
| 946 |
+
assert res.shape == (nrows - 1, ncols + r_idx_nlevels)
|
| 947 |
+
|
| 948 |
+
# No NaNs.
|
| 949 |
+
for r in range(len(res.index)):
|
| 950 |
+
for c in range(len(res.columns)):
|
| 951 |
+
assert res.iloc[r, c] is not np.nan
|
| 952 |
+
|
| 953 |
+
def test_duplicated_columns(self, path):
|
| 954 |
+
# see gh-5235
|
| 955 |
+
df = DataFrame([[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B"])
|
| 956 |
+
df.to_excel(path, "test1")
|
| 957 |
+
expected = DataFrame(
|
| 958 |
+
[[1, 2, 3], [1, 2, 3], [1, 2, 3]], columns=["A", "B", "B.1"]
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
# By default, we mangle.
|
| 962 |
+
result = pd.read_excel(path, sheet_name="test1", index_col=0)
|
| 963 |
+
tm.assert_frame_equal(result, expected)
|
| 964 |
+
|
| 965 |
+
# see gh-11007, gh-10970
|
| 966 |
+
df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"])
|
| 967 |
+
df.to_excel(path, "test1")
|
| 968 |
+
|
| 969 |
+
result = pd.read_excel(path, sheet_name="test1", index_col=0)
|
| 970 |
+
expected = DataFrame(
|
| 971 |
+
[[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"]
|
| 972 |
+
)
|
| 973 |
+
tm.assert_frame_equal(result, expected)
|
| 974 |
+
|
| 975 |
+
# see gh-10982
|
| 976 |
+
df.to_excel(path, "test1", index=False, header=False)
|
| 977 |
+
result = pd.read_excel(path, sheet_name="test1", header=None)
|
| 978 |
+
|
| 979 |
+
expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
|
| 980 |
+
tm.assert_frame_equal(result, expected)
|
| 981 |
+
|
| 982 |
+
def test_swapped_columns(self, path):
|
| 983 |
+
# Test for issue #5427.
|
| 984 |
+
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})
|
| 985 |
+
write_frame.to_excel(path, "test1", columns=["B", "A"])
|
| 986 |
+
|
| 987 |
+
read_frame = pd.read_excel(path, sheet_name="test1", header=0)
|
| 988 |
+
|
| 989 |
+
tm.assert_series_equal(write_frame["A"], read_frame["A"])
|
| 990 |
+
tm.assert_series_equal(write_frame["B"], read_frame["B"])
|
| 991 |
+
|
| 992 |
+
def test_invalid_columns(self, path):
|
| 993 |
+
# see gh-10982
|
| 994 |
+
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})
|
| 995 |
+
|
| 996 |
+
with pytest.raises(KeyError, match="Not all names specified"):
|
| 997 |
+
write_frame.to_excel(path, "test1", columns=["B", "C"])
|
| 998 |
+
|
| 999 |
+
with pytest.raises(
|
| 1000 |
+
KeyError, match="'passes columns are not ALL present dataframe'"
|
| 1001 |
+
):
|
| 1002 |
+
write_frame.to_excel(path, "test1", columns=["C", "D"])
|
| 1003 |
+
|
| 1004 |
+
@pytest.mark.parametrize(
|
| 1005 |
+
"to_excel_index,read_excel_index_col",
|
| 1006 |
+
[
|
| 1007 |
+
(True, 0), # Include index in write to file
|
| 1008 |
+
(False, None), # Dont include index in write to file
|
| 1009 |
+
],
|
| 1010 |
+
)
|
| 1011 |
+
def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):
|
| 1012 |
+
# GH 31677
|
| 1013 |
+
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2], "C": [3, 3, 3]})
|
| 1014 |
+
write_frame.to_excel(
|
| 1015 |
+
path, "col_subset_bug", columns=["A", "B"], index=to_excel_index
|
| 1016 |
+
)
|
| 1017 |
+
|
| 1018 |
+
expected = write_frame[["A", "B"]]
|
| 1019 |
+
read_frame = pd.read_excel(
|
| 1020 |
+
path, sheet_name="col_subset_bug", index_col=read_excel_index_col
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
tm.assert_frame_equal(expected, read_frame)
|
| 1024 |
+
|
| 1025 |
+
def test_comment_arg(self, path):
|
| 1026 |
+
# see gh-18735
|
| 1027 |
+
#
|
| 1028 |
+
# Test the comment argument functionality to pd.read_excel.
|
| 1029 |
+
|
| 1030 |
+
# Create file to read in.
|
| 1031 |
+
df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
|
| 1032 |
+
df.to_excel(path, "test_c")
|
| 1033 |
+
|
| 1034 |
+
# Read file without comment arg.
|
| 1035 |
+
result1 = pd.read_excel(path, sheet_name="test_c", index_col=0)
|
| 1036 |
+
|
| 1037 |
+
result1.iloc[1, 0] = None
|
| 1038 |
+
result1.iloc[1, 1] = None
|
| 1039 |
+
result1.iloc[2, 1] = None
|
| 1040 |
+
|
| 1041 |
+
result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
|
| 1042 |
+
tm.assert_frame_equal(result1, result2)
|
| 1043 |
+
|
| 1044 |
+
def test_comment_default(self, path):
|
| 1045 |
+
# Re issue #18735
|
| 1046 |
+
# Test the comment argument default to pd.read_excel
|
| 1047 |
+
|
| 1048 |
+
# Create file to read in
|
| 1049 |
+
df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
|
| 1050 |
+
df.to_excel(path, "test_c")
|
| 1051 |
+
|
| 1052 |
+
# Read file with default and explicit comment=None
|
| 1053 |
+
result1 = pd.read_excel(path, sheet_name="test_c")
|
| 1054 |
+
result2 = pd.read_excel(path, sheet_name="test_c", comment=None)
|
| 1055 |
+
tm.assert_frame_equal(result1, result2)
|
| 1056 |
+
|
| 1057 |
+
def test_comment_used(self, path):
|
| 1058 |
+
# see gh-18735
|
| 1059 |
+
#
|
| 1060 |
+
# Test the comment argument is working as expected when used.
|
| 1061 |
+
|
| 1062 |
+
# Create file to read in.
|
| 1063 |
+
df = DataFrame({"A": ["one", "#one", "one"], "B": ["two", "two", "#two"]})
|
| 1064 |
+
df.to_excel(path, "test_c")
|
| 1065 |
+
|
| 1066 |
+
# Test read_frame_comment against manually produced expected output.
|
| 1067 |
+
expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]})
|
| 1068 |
+
result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
|
| 1069 |
+
tm.assert_frame_equal(result, expected)
|
| 1070 |
+
|
| 1071 |
+
def test_comment_empty_line(self, path):
|
| 1072 |
+
# Re issue #18735
|
| 1073 |
+
# Test that pd.read_excel ignores commented lines at the end of file
|
| 1074 |
+
|
| 1075 |
+
df = DataFrame({"a": ["1", "#2"], "b": ["2", "3"]})
|
| 1076 |
+
df.to_excel(path, index=False)
|
| 1077 |
+
|
| 1078 |
+
# Test that all-comment lines at EoF are ignored
|
| 1079 |
+
expected = DataFrame({"a": [1], "b": [2]})
|
| 1080 |
+
result = pd.read_excel(path, comment="#")
|
| 1081 |
+
tm.assert_frame_equal(result, expected)
|
| 1082 |
+
|
| 1083 |
+
def test_datetimes(self, path):
|
| 1084 |
+
# Test writing and reading datetimes. For issue #9139. (xref #9185)
|
| 1085 |
+
datetimes = [
|
| 1086 |
+
datetime(2013, 1, 13, 1, 2, 3),
|
| 1087 |
+
datetime(2013, 1, 13, 2, 45, 56),
|
| 1088 |
+
datetime(2013, 1, 13, 4, 29, 49),
|
| 1089 |
+
datetime(2013, 1, 13, 6, 13, 42),
|
| 1090 |
+
datetime(2013, 1, 13, 7, 57, 35),
|
| 1091 |
+
datetime(2013, 1, 13, 9, 41, 28),
|
| 1092 |
+
datetime(2013, 1, 13, 11, 25, 21),
|
| 1093 |
+
datetime(2013, 1, 13, 13, 9, 14),
|
| 1094 |
+
datetime(2013, 1, 13, 14, 53, 7),
|
| 1095 |
+
datetime(2013, 1, 13, 16, 37, 0),
|
| 1096 |
+
datetime(2013, 1, 13, 18, 20, 52),
|
| 1097 |
+
]
|
| 1098 |
+
|
| 1099 |
+
write_frame = DataFrame({"A": datetimes})
|
| 1100 |
+
write_frame.to_excel(path, "Sheet1")
|
| 1101 |
+
read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)
|
| 1102 |
+
|
| 1103 |
+
tm.assert_series_equal(write_frame["A"], read_frame["A"])
|
| 1104 |
+
|
| 1105 |
+
def test_bytes_io(self, engine):
|
| 1106 |
+
# see gh-7074
|
| 1107 |
+
with BytesIO() as bio:
|
| 1108 |
+
df = DataFrame(np.random.randn(10, 2))
|
| 1109 |
+
|
| 1110 |
+
# Pass engine explicitly, as there is no file path to infer from.
|
| 1111 |
+
with ExcelWriter(bio, engine=engine) as writer:
|
| 1112 |
+
df.to_excel(writer)
|
| 1113 |
+
|
| 1114 |
+
bio.seek(0)
|
| 1115 |
+
reread_df = pd.read_excel(bio, index_col=0)
|
| 1116 |
+
tm.assert_frame_equal(df, reread_df)
|
| 1117 |
+
|
| 1118 |
+
def test_write_lists_dict(self, path):
|
| 1119 |
+
# see gh-8188.
|
| 1120 |
+
df = DataFrame(
|
| 1121 |
+
{
|
| 1122 |
+
"mixed": ["a", ["b", "c"], {"d": "e", "f": 2}],
|
| 1123 |
+
"numeric": [1, 2, 3.0],
|
| 1124 |
+
"str": ["apple", "banana", "cherry"],
|
| 1125 |
+
}
|
| 1126 |
+
)
|
| 1127 |
+
df.to_excel(path, "Sheet1")
|
| 1128 |
+
read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0)
|
| 1129 |
+
|
| 1130 |
+
expected = df.copy()
|
| 1131 |
+
expected.mixed = expected.mixed.apply(str)
|
| 1132 |
+
expected.numeric = expected.numeric.astype("int64")
|
| 1133 |
+
|
| 1134 |
+
tm.assert_frame_equal(read, expected)
|
| 1135 |
+
|
| 1136 |
+
def test_render_as_column_name(self, path):
|
| 1137 |
+
# see gh-34331
|
| 1138 |
+
df = DataFrame({"render": [1, 2], "data": [3, 4]})
|
| 1139 |
+
df.to_excel(path, "Sheet1")
|
| 1140 |
+
read = pd.read_excel(path, "Sheet1", index_col=0)
|
| 1141 |
+
expected = df
|
| 1142 |
+
tm.assert_frame_equal(read, expected)
|
| 1143 |
+
|
| 1144 |
+
def test_true_and_false_value_options(self, path):
|
| 1145 |
+
# see gh-13347
|
| 1146 |
+
df = DataFrame([["foo", "bar"]], columns=["col1", "col2"])
|
| 1147 |
+
expected = df.replace({"foo": True, "bar": False})
|
| 1148 |
+
|
| 1149 |
+
df.to_excel(path)
|
| 1150 |
+
read_frame = pd.read_excel(
|
| 1151 |
+
path, true_values=["foo"], false_values=["bar"], index_col=0
|
| 1152 |
+
)
|
| 1153 |
+
tm.assert_frame_equal(read_frame, expected)
|
| 1154 |
+
|
| 1155 |
+
def test_freeze_panes(self, path):
|
| 1156 |
+
# see gh-15160
|
| 1157 |
+
expected = DataFrame([[1, 2], [3, 4]], columns=["col1", "col2"])
|
| 1158 |
+
expected.to_excel(path, "Sheet1", freeze_panes=(1, 1))
|
| 1159 |
+
|
| 1160 |
+
result = pd.read_excel(path, index_col=0)
|
| 1161 |
+
tm.assert_frame_equal(result, expected)
|
| 1162 |
+
|
| 1163 |
+
def test_path_path_lib(self, engine, ext):
|
| 1164 |
+
df = tm.makeDataFrame()
|
| 1165 |
+
writer = partial(df.to_excel, engine=engine)
|
| 1166 |
+
|
| 1167 |
+
reader = partial(pd.read_excel, index_col=0)
|
| 1168 |
+
result = tm.round_trip_pathlib(writer, reader, path=f"foo{ext}")
|
| 1169 |
+
tm.assert_frame_equal(result, df)
|
| 1170 |
+
|
| 1171 |
+
def test_path_local_path(self, engine, ext):
|
| 1172 |
+
df = tm.makeDataFrame()
|
| 1173 |
+
writer = partial(df.to_excel, engine=engine)
|
| 1174 |
+
|
| 1175 |
+
reader = partial(pd.read_excel, index_col=0)
|
| 1176 |
+
result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}")
|
| 1177 |
+
tm.assert_frame_equal(result, df)
|
| 1178 |
+
|
| 1179 |
+
def test_merged_cell_custom_objects(self, path):
|
| 1180 |
+
# see GH-27006
|
| 1181 |
+
mi = MultiIndex.from_tuples(
|
| 1182 |
+
[
|
| 1183 |
+
(pd.Period("2018"), pd.Period("2018Q1")),
|
| 1184 |
+
(pd.Period("2018"), pd.Period("2018Q2")),
|
| 1185 |
+
]
|
| 1186 |
+
)
|
| 1187 |
+
expected = DataFrame(np.ones((2, 2), dtype="int64"), columns=mi)
|
| 1188 |
+
expected.to_excel(path)
|
| 1189 |
+
result = pd.read_excel(path, header=[0, 1], index_col=0)
|
| 1190 |
+
# need to convert PeriodIndexes to standard Indexes for assert equal
|
| 1191 |
+
expected.columns = expected.columns.set_levels(
|
| 1192 |
+
[[str(i) for i in mi.levels[0]], [str(i) for i in mi.levels[1]]],
|
| 1193 |
+
level=[0, 1],
|
| 1194 |
+
)
|
| 1195 |
+
tm.assert_frame_equal(result, expected)
|
| 1196 |
+
|
| 1197 |
+
@pytest.mark.parametrize("dtype", [None, object])
|
| 1198 |
+
def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path):
|
| 1199 |
+
# GH 27008, GH 7056
|
| 1200 |
+
tz = tz_aware_fixture
|
| 1201 |
+
data = pd.Timestamp("2019", tz=tz)
|
| 1202 |
+
df = DataFrame([data], dtype=dtype)
|
| 1203 |
+
with pytest.raises(ValueError, match="Excel does not support"):
|
| 1204 |
+
df.to_excel(path)
|
| 1205 |
+
|
| 1206 |
+
data = data.to_pydatetime()
|
| 1207 |
+
df = DataFrame([data], dtype=dtype)
|
| 1208 |
+
with pytest.raises(ValueError, match="Excel does not support"):
|
| 1209 |
+
df.to_excel(path)
|
| 1210 |
+
|
| 1211 |
+
def test_excel_duplicate_columns_with_names(self, path):
|
| 1212 |
+
# GH#39695
|
| 1213 |
+
df = DataFrame({"A": [0, 1], "B": [10, 11]})
|
| 1214 |
+
df.to_excel(path, columns=["A", "B", "A"], index=False)
|
| 1215 |
+
|
| 1216 |
+
result = pd.read_excel(path)
|
| 1217 |
+
expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])
|
| 1218 |
+
tm.assert_frame_equal(result, expected)
|
| 1219 |
+
|
| 1220 |
+
def test_if_sheet_exists_raises(self, ext):
|
| 1221 |
+
# GH 40230
|
| 1222 |
+
msg = "if_sheet_exists is only valid in append mode (mode='a')"
|
| 1223 |
+
|
| 1224 |
+
with tm.ensure_clean(ext) as f:
|
| 1225 |
+
with pytest.raises(ValueError, match=re.escape(msg)):
|
| 1226 |
+
ExcelWriter(f, if_sheet_exists="replace")
|
| 1227 |
+
|
| 1228 |
+
def test_excel_writer_empty_frame(self, engine, ext):
|
| 1229 |
+
# GH#45793
|
| 1230 |
+
with tm.ensure_clean(ext) as path:
|
| 1231 |
+
with ExcelWriter(path, engine=engine) as writer:
|
| 1232 |
+
DataFrame().to_excel(writer)
|
| 1233 |
+
result = pd.read_excel(path)
|
| 1234 |
+
expected = DataFrame()
|
| 1235 |
+
tm.assert_frame_equal(result, expected)
|
| 1236 |
+
|
| 1237 |
+
def test_to_excel_empty_frame(self, engine, ext):
|
| 1238 |
+
# GH#45793
|
| 1239 |
+
with tm.ensure_clean(ext) as path:
|
| 1240 |
+
DataFrame().to_excel(path, engine=engine)
|
| 1241 |
+
result = pd.read_excel(path)
|
| 1242 |
+
expected = DataFrame()
|
| 1243 |
+
tm.assert_frame_equal(result, expected)
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
class TestExcelWriterEngineTests:
|
| 1247 |
+
@pytest.mark.parametrize(
|
| 1248 |
+
"klass,ext",
|
| 1249 |
+
[
|
| 1250 |
+
pytest.param(_XlsxWriter, ".xlsx", marks=td.skip_if_no("xlsxwriter")),
|
| 1251 |
+
pytest.param(_OpenpyxlWriter, ".xlsx", marks=td.skip_if_no("openpyxl")),
|
| 1252 |
+
],
|
| 1253 |
+
)
|
| 1254 |
+
def test_ExcelWriter_dispatch(self, klass, ext):
|
| 1255 |
+
with tm.ensure_clean(ext) as path:
|
| 1256 |
+
with ExcelWriter(path) as writer:
|
| 1257 |
+
if ext == ".xlsx" and td.safe_import("xlsxwriter"):
|
| 1258 |
+
# xlsxwriter has preference over openpyxl if both installed
|
| 1259 |
+
assert isinstance(writer, _XlsxWriter)
|
| 1260 |
+
else:
|
| 1261 |
+
assert isinstance(writer, klass)
|
| 1262 |
+
|
| 1263 |
+
def test_ExcelWriter_dispatch_raises(self):
|
| 1264 |
+
with pytest.raises(ValueError, match="No engine"):
|
| 1265 |
+
ExcelWriter("nothing")
|
| 1266 |
+
|
| 1267 |
+
def test_register_writer(self):
|
| 1268 |
+
class DummyClass(ExcelWriter):
|
| 1269 |
+
called_save = False
|
| 1270 |
+
called_write_cells = False
|
| 1271 |
+
called_sheets = False
|
| 1272 |
+
_supported_extensions = ("xlsx", "xls")
|
| 1273 |
+
_engine = "dummy"
|
| 1274 |
+
|
| 1275 |
+
def book(self):
|
| 1276 |
+
pass
|
| 1277 |
+
|
| 1278 |
+
def _save(self):
|
| 1279 |
+
type(self).called_save = True
|
| 1280 |
+
|
| 1281 |
+
def _write_cells(self, *args, **kwargs):
|
| 1282 |
+
type(self).called_write_cells = True
|
| 1283 |
+
|
| 1284 |
+
@property
|
| 1285 |
+
def sheets(self):
|
| 1286 |
+
type(self).called_sheets = True
|
| 1287 |
+
|
| 1288 |
+
@classmethod
|
| 1289 |
+
def assert_called_and_reset(cls):
|
| 1290 |
+
assert cls.called_save
|
| 1291 |
+
assert cls.called_write_cells
|
| 1292 |
+
assert not cls.called_sheets
|
| 1293 |
+
cls.called_save = False
|
| 1294 |
+
cls.called_write_cells = False
|
| 1295 |
+
|
| 1296 |
+
register_writer(DummyClass)
|
| 1297 |
+
|
| 1298 |
+
with option_context("io.excel.xlsx.writer", "dummy"):
|
| 1299 |
+
path = "something.xlsx"
|
| 1300 |
+
with tm.ensure_clean(path) as filepath:
|
| 1301 |
+
with ExcelWriter(filepath) as writer:
|
| 1302 |
+
assert isinstance(writer, DummyClass)
|
| 1303 |
+
df = tm.makeCustomDataframe(1, 1)
|
| 1304 |
+
df.to_excel(filepath)
|
| 1305 |
+
DummyClass.assert_called_and_reset()
|
| 1306 |
+
|
| 1307 |
+
with tm.ensure_clean("something.xls") as filepath:
|
| 1308 |
+
df.to_excel(filepath, engine="dummy")
|
| 1309 |
+
DummyClass.assert_called_and_reset()
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
@td.skip_if_no("xlrd")
|
| 1313 |
+
@td.skip_if_no("openpyxl")
|
| 1314 |
+
class TestFSPath:
|
| 1315 |
+
def test_excelfile_fspath(self):
|
| 1316 |
+
with tm.ensure_clean("foo.xlsx") as path:
|
| 1317 |
+
df = DataFrame({"A": [1, 2]})
|
| 1318 |
+
df.to_excel(path)
|
| 1319 |
+
with ExcelFile(path) as xl:
|
| 1320 |
+
result = os.fspath(xl)
|
| 1321 |
+
assert result == path
|
| 1322 |
+
|
| 1323 |
+
def test_excelwriter_fspath(self):
|
| 1324 |
+
with tm.ensure_clean("foo.xlsx") as path:
|
| 1325 |
+
with ExcelWriter(path) as writer:
|
| 1326 |
+
assert os.fspath(writer) == str(path)
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
@pytest.mark.parametrize("klass", _writers.values())
|
| 1330 |
+
def test_subclass_attr(klass):
|
| 1331 |
+
# testing that subclasses of ExcelWriter don't have public attributes (issue 49602)
|
| 1332 |
+
attrs_base = {name for name in dir(ExcelWriter) if not name.startswith("_")}
|
| 1333 |
+
attrs_klass = {name for name in dir(klass) if not name.startswith("_")}
|
| 1334 |
+
assert not attrs_base.symmetric_difference(attrs_klass)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (7.35 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_c_parser_only.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_comment.cpython-310.pyc
ADDED
|
Binary file (4.13 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_compression.cpython-310.pyc
ADDED
|
Binary file (6.29 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_concatenate_chunks.cpython-310.pyc
ADDED
|
Binary file (1.36 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_converters.cpython-310.pyc
ADDED
|
Binary file (5.31 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_dialect.cpython-310.pyc
ADDED
|
Binary file (3.71 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_encoding.cpython-310.pyc
ADDED
|
Binary file (8.57 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_header.cpython-310.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_index_col.cpython-310.pyc
ADDED
|
Binary file (8.83 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_mangle_dupes.cpython-310.pyc
ADDED
|
Binary file (4.08 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_multi_thread.cpython-310.pyc
ADDED
|
Binary file (4.35 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_na_values.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_network.cpython-310.pyc
ADDED
|
Binary file (8.97 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_parse_dates.cpython-310.pyc
ADDED
|
Binary file (42.4 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_read_fwf.cpython-310.pyc
ADDED
|
Binary file (23.8 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_skiprows.cpython-310.pyc
ADDED
|
Binary file (7.66 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_textreader.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/__pycache__/test_upcast.cpython-310.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_chunksize.cpython-310.pyc
ADDED
|
Binary file (7.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_common_basic.cpython-310.pyc
ADDED
|
Binary file (21.4 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_data_list.cpython-310.pyc
ADDED
|
Binary file (2.24 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_decimal.cpython-310.pyc
ADDED
|
Binary file (1.68 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_file_buffer_url.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_float.cpython-310.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_index.cpython-310.pyc
ADDED
|
Binary file (5.92 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_inf.cpython-310.pyc
ADDED
|
Binary file (1.77 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_ints.cpython-310.pyc
ADDED
|
Binary file (4.92 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_iterator.cpython-310.pyc
ADDED
|
Binary file (2.96 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_read_errors.cpython-310.pyc
ADDED
|
Binary file (7.89 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/__pycache__/test_verbose.cpython-310.pyc
ADDED
|
Binary file (1.3 kB). View file
|
|
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_common_basic.py
ADDED
|
@@ -0,0 +1,864 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from inspect import signature
|
| 7 |
+
from io import StringIO
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from pandas.errors import (
|
| 16 |
+
EmptyDataError,
|
| 17 |
+
ParserError,
|
| 18 |
+
ParserWarning,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from pandas import (
|
| 22 |
+
DataFrame,
|
| 23 |
+
Index,
|
| 24 |
+
Timestamp,
|
| 25 |
+
compat,
|
| 26 |
+
)
|
| 27 |
+
import pandas._testing as tm
|
| 28 |
+
|
| 29 |
+
from pandas.io.parsers import TextFileReader
|
| 30 |
+
from pandas.io.parsers.c_parser_wrapper import CParserWrapper
|
| 31 |
+
|
| 32 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 33 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_override_set_noconvert_columns():
|
| 37 |
+
# see gh-17351
|
| 38 |
+
#
|
| 39 |
+
# Usecols needs to be sorted in _set_noconvert_columns based
|
| 40 |
+
# on the test_usecols_with_parse_dates test from test_usecols.py
|
| 41 |
+
class MyTextFileReader(TextFileReader):
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
self._currow = 0
|
| 44 |
+
self.squeeze = False
|
| 45 |
+
|
| 46 |
+
class MyCParserWrapper(CParserWrapper):
|
| 47 |
+
def _set_noconvert_columns(self):
|
| 48 |
+
if self.usecols_dtype == "integer":
|
| 49 |
+
# self.usecols is a set, which is documented as unordered
|
| 50 |
+
# but in practice, a CPython set of integers is sorted.
|
| 51 |
+
# In other implementations this assumption does not hold.
|
| 52 |
+
# The following code simulates a different order, which
|
| 53 |
+
# before GH 17351 would cause the wrong columns to be
|
| 54 |
+
# converted via the parse_dates parameter
|
| 55 |
+
self.usecols = list(self.usecols)
|
| 56 |
+
self.usecols.reverse()
|
| 57 |
+
return CParserWrapper._set_noconvert_columns(self)
|
| 58 |
+
|
| 59 |
+
data = """a,b,c,d,e
|
| 60 |
+
0,1,2014-01-01,09:00,4
|
| 61 |
+
0,1,2014-01-02,10:00,4"""
|
| 62 |
+
|
| 63 |
+
parse_dates = [[1, 2]]
|
| 64 |
+
cols = {
|
| 65 |
+
"a": [0, 0],
|
| 66 |
+
"c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")],
|
| 67 |
+
}
|
| 68 |
+
expected = DataFrame(cols, columns=["c_d", "a"])
|
| 69 |
+
|
| 70 |
+
parser = MyTextFileReader()
|
| 71 |
+
parser.options = {
|
| 72 |
+
"usecols": [0, 2, 3],
|
| 73 |
+
"parse_dates": parse_dates,
|
| 74 |
+
"delimiter": ",",
|
| 75 |
+
}
|
| 76 |
+
parser.engine = "c"
|
| 77 |
+
parser._engine = MyCParserWrapper(StringIO(data), **parser.options)
|
| 78 |
+
|
| 79 |
+
result = parser.read()
|
| 80 |
+
tm.assert_frame_equal(result, expected)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_read_csv_local(all_parsers, csv1):
|
| 84 |
+
prefix = "file:///" if compat.is_platform_windows() else "file://"
|
| 85 |
+
parser = all_parsers
|
| 86 |
+
|
| 87 |
+
fname = prefix + str(os.path.abspath(csv1))
|
| 88 |
+
result = parser.read_csv(fname, index_col=0, parse_dates=True)
|
| 89 |
+
|
| 90 |
+
expected = DataFrame(
|
| 91 |
+
[
|
| 92 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738],
|
| 93 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549],
|
| 94 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270],
|
| 95 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253],
|
| 96 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469],
|
| 97 |
+
[0.836649, 0.246462, 0.588542635376, 1.062782],
|
| 98 |
+
[-0.157161, 1.340307, 1.1957779562, -1.097007],
|
| 99 |
+
],
|
| 100 |
+
columns=["A", "B", "C", "D"],
|
| 101 |
+
index=Index(
|
| 102 |
+
[
|
| 103 |
+
datetime(2000, 1, 3),
|
| 104 |
+
datetime(2000, 1, 4),
|
| 105 |
+
datetime(2000, 1, 5),
|
| 106 |
+
datetime(2000, 1, 6),
|
| 107 |
+
datetime(2000, 1, 7),
|
| 108 |
+
datetime(2000, 1, 10),
|
| 109 |
+
datetime(2000, 1, 11),
|
| 110 |
+
],
|
| 111 |
+
name="index",
|
| 112 |
+
),
|
| 113 |
+
)
|
| 114 |
+
tm.assert_frame_equal(result, expected)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@xfail_pyarrow
|
| 118 |
+
def test_1000_sep(all_parsers):
|
| 119 |
+
parser = all_parsers
|
| 120 |
+
data = """A|B|C
|
| 121 |
+
1|2,334|5
|
| 122 |
+
10|13|10.
|
| 123 |
+
"""
|
| 124 |
+
expected = DataFrame({"A": [1, 10], "B": [2334, 13], "C": [5, 10.0]})
|
| 125 |
+
|
| 126 |
+
result = parser.read_csv(StringIO(data), sep="|", thousands=",")
|
| 127 |
+
tm.assert_frame_equal(result, expected)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@xfail_pyarrow
|
| 131 |
+
def test_unnamed_columns(all_parsers):
|
| 132 |
+
data = """A,B,C,,
|
| 133 |
+
1,2,3,4,5
|
| 134 |
+
6,7,8,9,10
|
| 135 |
+
11,12,13,14,15
|
| 136 |
+
"""
|
| 137 |
+
parser = all_parsers
|
| 138 |
+
expected = DataFrame(
|
| 139 |
+
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]],
|
| 140 |
+
dtype=np.int64,
|
| 141 |
+
columns=["A", "B", "C", "Unnamed: 3", "Unnamed: 4"],
|
| 142 |
+
)
|
| 143 |
+
result = parser.read_csv(StringIO(data))
|
| 144 |
+
tm.assert_frame_equal(result, expected)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_csv_mixed_type(all_parsers):
|
| 148 |
+
data = """A,B,C
|
| 149 |
+
a,1,2
|
| 150 |
+
b,3,4
|
| 151 |
+
c,4,5
|
| 152 |
+
"""
|
| 153 |
+
parser = all_parsers
|
| 154 |
+
expected = DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]})
|
| 155 |
+
result = parser.read_csv(StringIO(data))
|
| 156 |
+
tm.assert_frame_equal(result, expected)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@xfail_pyarrow
|
| 160 |
+
def test_read_csv_low_memory_no_rows_with_index(all_parsers):
|
| 161 |
+
# see gh-21141
|
| 162 |
+
parser = all_parsers
|
| 163 |
+
|
| 164 |
+
if not parser.low_memory:
|
| 165 |
+
pytest.skip("This is a low-memory specific test")
|
| 166 |
+
|
| 167 |
+
data = """A,B,C
|
| 168 |
+
1,1,1,2
|
| 169 |
+
2,2,3,4
|
| 170 |
+
3,3,4,5
|
| 171 |
+
"""
|
| 172 |
+
result = parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0)
|
| 173 |
+
expected = DataFrame(columns=["A", "B", "C"])
|
| 174 |
+
tm.assert_frame_equal(result, expected)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_read_csv_dataframe(all_parsers, csv1):
|
| 178 |
+
parser = all_parsers
|
| 179 |
+
result = parser.read_csv(csv1, index_col=0, parse_dates=True)
|
| 180 |
+
|
| 181 |
+
expected = DataFrame(
|
| 182 |
+
[
|
| 183 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738],
|
| 184 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549],
|
| 185 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270],
|
| 186 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253],
|
| 187 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469],
|
| 188 |
+
[0.836649, 0.246462, 0.588542635376, 1.062782],
|
| 189 |
+
[-0.157161, 1.340307, 1.1957779562, -1.097007],
|
| 190 |
+
],
|
| 191 |
+
columns=["A", "B", "C", "D"],
|
| 192 |
+
index=Index(
|
| 193 |
+
[
|
| 194 |
+
datetime(2000, 1, 3),
|
| 195 |
+
datetime(2000, 1, 4),
|
| 196 |
+
datetime(2000, 1, 5),
|
| 197 |
+
datetime(2000, 1, 6),
|
| 198 |
+
datetime(2000, 1, 7),
|
| 199 |
+
datetime(2000, 1, 10),
|
| 200 |
+
datetime(2000, 1, 11),
|
| 201 |
+
],
|
| 202 |
+
name="index",
|
| 203 |
+
),
|
| 204 |
+
)
|
| 205 |
+
tm.assert_frame_equal(result, expected)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@xfail_pyarrow
|
| 209 |
+
@pytest.mark.parametrize("nrows", [3, 3.0])
|
| 210 |
+
def test_read_nrows(all_parsers, nrows):
|
| 211 |
+
# see gh-10476
|
| 212 |
+
data = """index,A,B,C,D
|
| 213 |
+
foo,2,3,4,5
|
| 214 |
+
bar,7,8,9,10
|
| 215 |
+
baz,12,13,14,15
|
| 216 |
+
qux,12,13,14,15
|
| 217 |
+
foo2,12,13,14,15
|
| 218 |
+
bar2,12,13,14,15
|
| 219 |
+
"""
|
| 220 |
+
expected = DataFrame(
|
| 221 |
+
[["foo", 2, 3, 4, 5], ["bar", 7, 8, 9, 10], ["baz", 12, 13, 14, 15]],
|
| 222 |
+
columns=["index", "A", "B", "C", "D"],
|
| 223 |
+
)
|
| 224 |
+
parser = all_parsers
|
| 225 |
+
|
| 226 |
+
result = parser.read_csv(StringIO(data), nrows=nrows)
|
| 227 |
+
tm.assert_frame_equal(result, expected)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@xfail_pyarrow
|
| 231 |
+
@pytest.mark.parametrize("nrows", [1.2, "foo", -1])
|
| 232 |
+
def test_read_nrows_bad(all_parsers, nrows):
|
| 233 |
+
data = """index,A,B,C,D
|
| 234 |
+
foo,2,3,4,5
|
| 235 |
+
bar,7,8,9,10
|
| 236 |
+
baz,12,13,14,15
|
| 237 |
+
qux,12,13,14,15
|
| 238 |
+
foo2,12,13,14,15
|
| 239 |
+
bar2,12,13,14,15
|
| 240 |
+
"""
|
| 241 |
+
msg = r"'nrows' must be an integer >=0"
|
| 242 |
+
parser = all_parsers
|
| 243 |
+
|
| 244 |
+
with pytest.raises(ValueError, match=msg):
|
| 245 |
+
parser.read_csv(StringIO(data), nrows=nrows)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_nrows_skipfooter_errors(all_parsers):
|
| 249 |
+
msg = "'skipfooter' not supported with 'nrows'"
|
| 250 |
+
data = "a\n1\n2\n3\n4\n5\n6"
|
| 251 |
+
parser = all_parsers
|
| 252 |
+
|
| 253 |
+
with pytest.raises(ValueError, match=msg):
|
| 254 |
+
parser.read_csv(StringIO(data), skipfooter=1, nrows=5)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@xfail_pyarrow
|
| 258 |
+
def test_missing_trailing_delimiters(all_parsers):
|
| 259 |
+
parser = all_parsers
|
| 260 |
+
data = """A,B,C,D
|
| 261 |
+
1,2,3,4
|
| 262 |
+
1,3,3,
|
| 263 |
+
1,4,5"""
|
| 264 |
+
|
| 265 |
+
result = parser.read_csv(StringIO(data))
|
| 266 |
+
expected = DataFrame(
|
| 267 |
+
[[1, 2, 3, 4], [1, 3, 3, np.nan], [1, 4, 5, np.nan]],
|
| 268 |
+
columns=["A", "B", "C", "D"],
|
| 269 |
+
)
|
| 270 |
+
tm.assert_frame_equal(result, expected)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@xfail_pyarrow
|
| 274 |
+
def test_skip_initial_space(all_parsers):
|
| 275 |
+
data = (
|
| 276 |
+
'"09-Apr-2012", "01:10:18.300", 2456026.548822908, 12849, '
|
| 277 |
+
"1.00361, 1.12551, 330.65659, 0355626618.16711, 73.48821, "
|
| 278 |
+
"314.11625, 1917.09447, 179.71425, 80.000, 240.000, -350, "
|
| 279 |
+
"70.06056, 344.98370, 1, 1, -0.689265, -0.692787, "
|
| 280 |
+
"0.212036, 14.7674, 41.605, -9999.0, -9999.0, "
|
| 281 |
+
"-9999.0, -9999.0, -9999.0, -9999.0, 000, 012, 128"
|
| 282 |
+
)
|
| 283 |
+
parser = all_parsers
|
| 284 |
+
|
| 285 |
+
result = parser.read_csv(
|
| 286 |
+
StringIO(data),
|
| 287 |
+
names=list(range(33)),
|
| 288 |
+
header=None,
|
| 289 |
+
na_values=["-9999.0"],
|
| 290 |
+
skipinitialspace=True,
|
| 291 |
+
)
|
| 292 |
+
expected = DataFrame(
|
| 293 |
+
[
|
| 294 |
+
[
|
| 295 |
+
"09-Apr-2012",
|
| 296 |
+
"01:10:18.300",
|
| 297 |
+
2456026.548822908,
|
| 298 |
+
12849,
|
| 299 |
+
1.00361,
|
| 300 |
+
1.12551,
|
| 301 |
+
330.65659,
|
| 302 |
+
355626618.16711,
|
| 303 |
+
73.48821,
|
| 304 |
+
314.11625,
|
| 305 |
+
1917.09447,
|
| 306 |
+
179.71425,
|
| 307 |
+
80.0,
|
| 308 |
+
240.0,
|
| 309 |
+
-350,
|
| 310 |
+
70.06056,
|
| 311 |
+
344.9837,
|
| 312 |
+
1,
|
| 313 |
+
1,
|
| 314 |
+
-0.689265,
|
| 315 |
+
-0.692787,
|
| 316 |
+
0.212036,
|
| 317 |
+
14.7674,
|
| 318 |
+
41.605,
|
| 319 |
+
np.nan,
|
| 320 |
+
np.nan,
|
| 321 |
+
np.nan,
|
| 322 |
+
np.nan,
|
| 323 |
+
np.nan,
|
| 324 |
+
np.nan,
|
| 325 |
+
0,
|
| 326 |
+
12,
|
| 327 |
+
128,
|
| 328 |
+
]
|
| 329 |
+
]
|
| 330 |
+
)
|
| 331 |
+
tm.assert_frame_equal(result, expected)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@xfail_pyarrow
|
| 335 |
+
def test_trailing_delimiters(all_parsers):
|
| 336 |
+
# see gh-2442
|
| 337 |
+
data = """A,B,C
|
| 338 |
+
1,2,3,
|
| 339 |
+
4,5,6,
|
| 340 |
+
7,8,9,"""
|
| 341 |
+
parser = all_parsers
|
| 342 |
+
result = parser.read_csv(StringIO(data), index_col=False)
|
| 343 |
+
|
| 344 |
+
expected = DataFrame({"A": [1, 4, 7], "B": [2, 5, 8], "C": [3, 6, 9]})
|
| 345 |
+
tm.assert_frame_equal(result, expected)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_escapechar(all_parsers):
|
| 349 |
+
# https://stackoverflow.com/questions/13824840/feature-request-for-
|
| 350 |
+
# pandas-read-csv
|
| 351 |
+
data = '''SEARCH_TERM,ACTUAL_URL
|
| 352 |
+
"bra tv board","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
|
| 353 |
+
"tv p\xc3\xa5 hjul","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"
|
| 354 |
+
"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"''' # noqa:E501
|
| 355 |
+
|
| 356 |
+
parser = all_parsers
|
| 357 |
+
result = parser.read_csv(
|
| 358 |
+
StringIO(data), escapechar="\\", quotechar='"', encoding="utf-8"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
assert result["SEARCH_TERM"][2] == 'SLAGBORD, "Bergslagen", IKEA:s 1700-tals series'
|
| 362 |
+
|
| 363 |
+
tm.assert_index_equal(result.columns, Index(["SEARCH_TERM", "ACTUAL_URL"]))
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@xfail_pyarrow
|
| 367 |
+
def test_ignore_leading_whitespace(all_parsers):
|
| 368 |
+
# see gh-3374, gh-6607
|
| 369 |
+
parser = all_parsers
|
| 370 |
+
data = " a b c\n 1 2 3\n 4 5 6\n 7 8 9"
|
| 371 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 372 |
+
|
| 373 |
+
expected = DataFrame({"a": [1, 4, 7], "b": [2, 5, 8], "c": [3, 6, 9]})
|
| 374 |
+
tm.assert_frame_equal(result, expected)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@xfail_pyarrow
|
| 378 |
+
@pytest.mark.parametrize("usecols", [None, [0, 1], ["a", "b"]])
|
| 379 |
+
def test_uneven_lines_with_usecols(all_parsers, usecols):
|
| 380 |
+
# see gh-12203
|
| 381 |
+
parser = all_parsers
|
| 382 |
+
data = r"""a,b,c
|
| 383 |
+
0,1,2
|
| 384 |
+
3,4,5,6,7
|
| 385 |
+
8,9,10"""
|
| 386 |
+
|
| 387 |
+
if usecols is None:
|
| 388 |
+
# Make sure that an error is still raised
|
| 389 |
+
# when the "usecols" parameter is not provided.
|
| 390 |
+
msg = r"Expected \d+ fields in line \d+, saw \d+"
|
| 391 |
+
with pytest.raises(ParserError, match=msg):
|
| 392 |
+
parser.read_csv(StringIO(data))
|
| 393 |
+
else:
|
| 394 |
+
expected = DataFrame({"a": [0, 3, 8], "b": [1, 4, 9]})
|
| 395 |
+
|
| 396 |
+
result = parser.read_csv(StringIO(data), usecols=usecols)
|
| 397 |
+
tm.assert_frame_equal(result, expected)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@xfail_pyarrow
|
| 401 |
+
@pytest.mark.parametrize(
|
| 402 |
+
"data,kwargs,expected",
|
| 403 |
+
[
|
| 404 |
+
# First, check to see that the response of parser when faced with no
|
| 405 |
+
# provided columns raises the correct error, with or without usecols.
|
| 406 |
+
("", {}, None),
|
| 407 |
+
("", {"usecols": ["X"]}, None),
|
| 408 |
+
(
|
| 409 |
+
",,",
|
| 410 |
+
{"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]},
|
| 411 |
+
DataFrame(columns=["X"], index=[0], dtype=np.float64),
|
| 412 |
+
),
|
| 413 |
+
(
|
| 414 |
+
"",
|
| 415 |
+
{"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]},
|
| 416 |
+
DataFrame(columns=["X"]),
|
| 417 |
+
),
|
| 418 |
+
],
|
| 419 |
+
)
|
| 420 |
+
def test_read_empty_with_usecols(all_parsers, data, kwargs, expected):
|
| 421 |
+
# see gh-12493
|
| 422 |
+
parser = all_parsers
|
| 423 |
+
|
| 424 |
+
if expected is None:
|
| 425 |
+
msg = "No columns to parse from file"
|
| 426 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 427 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 428 |
+
else:
|
| 429 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 430 |
+
tm.assert_frame_equal(result, expected)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@xfail_pyarrow
|
| 434 |
+
@pytest.mark.parametrize(
|
| 435 |
+
"kwargs,expected",
|
| 436 |
+
[
|
| 437 |
+
# gh-8661, gh-8679: this should ignore six lines, including
|
| 438 |
+
# lines with trailing whitespace and blank lines.
|
| 439 |
+
(
|
| 440 |
+
{
|
| 441 |
+
"header": None,
|
| 442 |
+
"delim_whitespace": True,
|
| 443 |
+
"skiprows": [0, 1, 2, 3, 5, 6],
|
| 444 |
+
"skip_blank_lines": True,
|
| 445 |
+
},
|
| 446 |
+
DataFrame([[1.0, 2.0, 4.0], [5.1, np.nan, 10.0]]),
|
| 447 |
+
),
|
| 448 |
+
# gh-8983: test skipping set of rows after a row with trailing spaces.
|
| 449 |
+
(
|
| 450 |
+
{
|
| 451 |
+
"delim_whitespace": True,
|
| 452 |
+
"skiprows": [1, 2, 3, 5, 6],
|
| 453 |
+
"skip_blank_lines": True,
|
| 454 |
+
},
|
| 455 |
+
DataFrame({"A": [1.0, 5.1], "B": [2.0, np.nan], "C": [4.0, 10]}),
|
| 456 |
+
),
|
| 457 |
+
],
|
| 458 |
+
)
|
| 459 |
+
def test_trailing_spaces(all_parsers, kwargs, expected):
|
| 460 |
+
data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa:E501
|
| 461 |
+
parser = all_parsers
|
| 462 |
+
|
| 463 |
+
result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs)
|
| 464 |
+
tm.assert_frame_equal(result, expected)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def test_raise_on_sep_with_delim_whitespace(all_parsers):
|
| 468 |
+
# see gh-6607
|
| 469 |
+
data = "a b c\n1 2 3"
|
| 470 |
+
parser = all_parsers
|
| 471 |
+
|
| 472 |
+
with pytest.raises(ValueError, match="you can only specify one"):
|
| 473 |
+
parser.read_csv(StringIO(data), sep=r"\s", delim_whitespace=True)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def test_read_filepath_or_buffer(all_parsers):
|
| 477 |
+
# see gh-43366
|
| 478 |
+
parser = all_parsers
|
| 479 |
+
|
| 480 |
+
with pytest.raises(TypeError, match="Expected file path name or file-like"):
|
| 481 |
+
parser.read_csv(filepath_or_buffer=b"input")
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@xfail_pyarrow
|
| 485 |
+
@pytest.mark.parametrize("delim_whitespace", [True, False])
|
| 486 |
+
def test_single_char_leading_whitespace(all_parsers, delim_whitespace):
|
| 487 |
+
# see gh-9710
|
| 488 |
+
parser = all_parsers
|
| 489 |
+
data = """\
|
| 490 |
+
MyColumn
|
| 491 |
+
a
|
| 492 |
+
b
|
| 493 |
+
a
|
| 494 |
+
b\n"""
|
| 495 |
+
|
| 496 |
+
expected = DataFrame({"MyColumn": list("abab")})
|
| 497 |
+
result = parser.read_csv(
|
| 498 |
+
StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace
|
| 499 |
+
)
|
| 500 |
+
tm.assert_frame_equal(result, expected)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
# Skip for now, actually only one test fails though, but its tricky to xfail
|
| 504 |
+
@skip_pyarrow
|
| 505 |
+
@pytest.mark.parametrize(
|
| 506 |
+
"sep,skip_blank_lines,exp_data",
|
| 507 |
+
[
|
| 508 |
+
(",", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]),
|
| 509 |
+
(r"\s+", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]),
|
| 510 |
+
(
|
| 511 |
+
",",
|
| 512 |
+
False,
|
| 513 |
+
[
|
| 514 |
+
[1.0, 2.0, 4.0],
|
| 515 |
+
[np.nan, np.nan, np.nan],
|
| 516 |
+
[np.nan, np.nan, np.nan],
|
| 517 |
+
[5.0, np.nan, 10.0],
|
| 518 |
+
[np.nan, np.nan, np.nan],
|
| 519 |
+
[-70.0, 0.4, 1.0],
|
| 520 |
+
],
|
| 521 |
+
),
|
| 522 |
+
],
|
| 523 |
+
)
|
| 524 |
+
def test_empty_lines(all_parsers, sep, skip_blank_lines, exp_data):
|
| 525 |
+
parser = all_parsers
|
| 526 |
+
data = """\
|
| 527 |
+
A,B,C
|
| 528 |
+
1,2.,4.
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
5.,NaN,10.0
|
| 532 |
+
|
| 533 |
+
-70,.4,1
|
| 534 |
+
"""
|
| 535 |
+
|
| 536 |
+
if sep == r"\s+":
|
| 537 |
+
data = data.replace(",", " ")
|
| 538 |
+
|
| 539 |
+
result = parser.read_csv(StringIO(data), sep=sep, skip_blank_lines=skip_blank_lines)
|
| 540 |
+
expected = DataFrame(exp_data, columns=["A", "B", "C"])
|
| 541 |
+
tm.assert_frame_equal(result, expected)
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
@xfail_pyarrow
|
| 545 |
+
def test_whitespace_lines(all_parsers):
|
| 546 |
+
parser = all_parsers
|
| 547 |
+
data = """
|
| 548 |
+
|
| 549 |
+
\t \t\t
|
| 550 |
+
\t
|
| 551 |
+
A,B,C
|
| 552 |
+
\t 1,2.,4.
|
| 553 |
+
5.,NaN,10.0
|
| 554 |
+
"""
|
| 555 |
+
expected = DataFrame([[1, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"])
|
| 556 |
+
result = parser.read_csv(StringIO(data))
|
| 557 |
+
tm.assert_frame_equal(result, expected)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@xfail_pyarrow
|
| 561 |
+
@pytest.mark.parametrize(
|
| 562 |
+
"data,expected",
|
| 563 |
+
[
|
| 564 |
+
(
|
| 565 |
+
""" A B C D
|
| 566 |
+
a 1 2 3 4
|
| 567 |
+
b 1 2 3 4
|
| 568 |
+
c 1 2 3 4
|
| 569 |
+
""",
|
| 570 |
+
DataFrame(
|
| 571 |
+
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
|
| 572 |
+
columns=["A", "B", "C", "D"],
|
| 573 |
+
index=["a", "b", "c"],
|
| 574 |
+
),
|
| 575 |
+
),
|
| 576 |
+
(
|
| 577 |
+
" a b c\n1 2 3 \n4 5 6\n 7 8 9",
|
| 578 |
+
DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"]),
|
| 579 |
+
),
|
| 580 |
+
],
|
| 581 |
+
)
|
| 582 |
+
def test_whitespace_regex_separator(all_parsers, data, expected):
|
| 583 |
+
# see gh-6607
|
| 584 |
+
parser = all_parsers
|
| 585 |
+
result = parser.read_csv(StringIO(data), sep=r"\s+")
|
| 586 |
+
tm.assert_frame_equal(result, expected)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def test_sub_character(all_parsers, csv_dir_path):
|
| 590 |
+
# see gh-16893
|
| 591 |
+
filename = os.path.join(csv_dir_path, "sub_char.csv")
|
| 592 |
+
expected = DataFrame([[1, 2, 3]], columns=["a", "\x1ab", "c"])
|
| 593 |
+
|
| 594 |
+
parser = all_parsers
|
| 595 |
+
result = parser.read_csv(filename)
|
| 596 |
+
tm.assert_frame_equal(result, expected)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
@pytest.mark.parametrize("filename", ["sé-es-vé.csv", "ru-sй.csv", "中文文件名.csv"])
|
| 600 |
+
def test_filename_with_special_chars(all_parsers, filename):
|
| 601 |
+
# see gh-15086.
|
| 602 |
+
parser = all_parsers
|
| 603 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 604 |
+
|
| 605 |
+
with tm.ensure_clean(filename) as path:
|
| 606 |
+
df.to_csv(path, index=False)
|
| 607 |
+
|
| 608 |
+
result = parser.read_csv(path)
|
| 609 |
+
tm.assert_frame_equal(result, df)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def test_read_table_same_signature_as_read_csv(all_parsers):
|
| 613 |
+
# GH-34976
|
| 614 |
+
parser = all_parsers
|
| 615 |
+
|
| 616 |
+
table_sign = signature(parser.read_table)
|
| 617 |
+
csv_sign = signature(parser.read_csv)
|
| 618 |
+
|
| 619 |
+
assert table_sign.parameters.keys() == csv_sign.parameters.keys()
|
| 620 |
+
assert table_sign.return_annotation == csv_sign.return_annotation
|
| 621 |
+
|
| 622 |
+
for key, csv_param in csv_sign.parameters.items():
|
| 623 |
+
table_param = table_sign.parameters[key]
|
| 624 |
+
if key == "sep":
|
| 625 |
+
assert csv_param.default == ","
|
| 626 |
+
assert table_param.default == "\t"
|
| 627 |
+
assert table_param.annotation == csv_param.annotation
|
| 628 |
+
assert table_param.kind == csv_param.kind
|
| 629 |
+
continue
|
| 630 |
+
|
| 631 |
+
assert table_param == csv_param
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_read_table_equivalency_to_read_csv(all_parsers):
|
| 635 |
+
# see gh-21948
|
| 636 |
+
# As of 0.25.0, read_table is undeprecated
|
| 637 |
+
parser = all_parsers
|
| 638 |
+
data = "a\tb\n1\t2\n3\t4"
|
| 639 |
+
expected = parser.read_csv(StringIO(data), sep="\t")
|
| 640 |
+
result = parser.read_table(StringIO(data))
|
| 641 |
+
tm.assert_frame_equal(result, expected)
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
@pytest.mark.parametrize("read_func", ["read_csv", "read_table"])
|
| 645 |
+
def test_read_csv_and_table_sys_setprofile(all_parsers, read_func):
|
| 646 |
+
# GH#41069
|
| 647 |
+
parser = all_parsers
|
| 648 |
+
data = "a b\n0 1"
|
| 649 |
+
|
| 650 |
+
sys.setprofile(lambda *a, **k: None)
|
| 651 |
+
result = getattr(parser, read_func)(StringIO(data))
|
| 652 |
+
sys.setprofile(None)
|
| 653 |
+
|
| 654 |
+
expected = DataFrame({"a b": ["0 1"]})
|
| 655 |
+
tm.assert_frame_equal(result, expected)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
@xfail_pyarrow
|
| 659 |
+
def test_first_row_bom(all_parsers):
|
| 660 |
+
# see gh-26545
|
| 661 |
+
parser = all_parsers
|
| 662 |
+
data = '''\ufeff"Head1"\t"Head2"\t"Head3"'''
|
| 663 |
+
|
| 664 |
+
result = parser.read_csv(StringIO(data), delimiter="\t")
|
| 665 |
+
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
|
| 666 |
+
tm.assert_frame_equal(result, expected)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
@xfail_pyarrow
|
| 670 |
+
def test_first_row_bom_unquoted(all_parsers):
|
| 671 |
+
# see gh-36343
|
| 672 |
+
parser = all_parsers
|
| 673 |
+
data = """\ufeffHead1\tHead2\tHead3"""
|
| 674 |
+
|
| 675 |
+
result = parser.read_csv(StringIO(data), delimiter="\t")
|
| 676 |
+
expected = DataFrame(columns=["Head1", "Head2", "Head3"])
|
| 677 |
+
tm.assert_frame_equal(result, expected)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@xfail_pyarrow
|
| 681 |
+
@pytest.mark.parametrize("nrows", range(1, 6))
|
| 682 |
+
def test_blank_lines_between_header_and_data_rows(all_parsers, nrows):
|
| 683 |
+
# GH 28071
|
| 684 |
+
ref = DataFrame(
|
| 685 |
+
[[np.nan, np.nan], [np.nan, np.nan], [1, 2], [np.nan, np.nan], [3, 4]],
|
| 686 |
+
columns=list("ab"),
|
| 687 |
+
)
|
| 688 |
+
csv = "\nheader\n\na,b\n\n\n1,2\n\n3,4"
|
| 689 |
+
parser = all_parsers
|
| 690 |
+
df = parser.read_csv(StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False)
|
| 691 |
+
tm.assert_frame_equal(df, ref[:nrows])
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@xfail_pyarrow
|
| 695 |
+
def test_no_header_two_extra_columns(all_parsers):
|
| 696 |
+
# GH 26218
|
| 697 |
+
column_names = ["one", "two", "three"]
|
| 698 |
+
ref = DataFrame([["foo", "bar", "baz"]], columns=column_names)
|
| 699 |
+
stream = StringIO("foo,bar,baz,bam,blah")
|
| 700 |
+
parser = all_parsers
|
| 701 |
+
df = parser.read_csv_check_warnings(
|
| 702 |
+
ParserWarning,
|
| 703 |
+
"Length of header or names does not match length of data. "
|
| 704 |
+
"This leads to a loss of data with index_col=False.",
|
| 705 |
+
stream,
|
| 706 |
+
header=None,
|
| 707 |
+
names=column_names,
|
| 708 |
+
index_col=False,
|
| 709 |
+
)
|
| 710 |
+
tm.assert_frame_equal(df, ref)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def test_read_csv_names_not_accepting_sets(all_parsers):
|
| 714 |
+
# GH 34946
|
| 715 |
+
data = """\
|
| 716 |
+
1,2,3
|
| 717 |
+
4,5,6\n"""
|
| 718 |
+
parser = all_parsers
|
| 719 |
+
with pytest.raises(ValueError, match="Names should be an ordered collection."):
|
| 720 |
+
parser.read_csv(StringIO(data), names=set("QAZ"))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
@xfail_pyarrow
|
| 724 |
+
def test_read_table_delim_whitespace_default_sep(all_parsers):
|
| 725 |
+
# GH: 35958
|
| 726 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 727 |
+
parser = all_parsers
|
| 728 |
+
result = parser.read_table(f, delim_whitespace=True)
|
| 729 |
+
expected = DataFrame({"a": [1, 4], "b": [-2, 5], "c": [-3, 6]})
|
| 730 |
+
tm.assert_frame_equal(result, expected)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
@pytest.mark.parametrize("delimiter", [",", "\t"])
|
| 734 |
+
def test_read_csv_delim_whitespace_non_default_sep(all_parsers, delimiter):
|
| 735 |
+
# GH: 35958
|
| 736 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 737 |
+
parser = all_parsers
|
| 738 |
+
msg = (
|
| 739 |
+
"Specified a delimiter with both sep and "
|
| 740 |
+
"delim_whitespace=True; you can only specify one."
|
| 741 |
+
)
|
| 742 |
+
with pytest.raises(ValueError, match=msg):
|
| 743 |
+
parser.read_csv(f, delim_whitespace=True, sep=delimiter)
|
| 744 |
+
|
| 745 |
+
with pytest.raises(ValueError, match=msg):
|
| 746 |
+
parser.read_csv(f, delim_whitespace=True, delimiter=delimiter)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def test_read_csv_delimiter_and_sep_no_default(all_parsers):
|
| 750 |
+
# GH#39823
|
| 751 |
+
f = StringIO("a,b\n1,2")
|
| 752 |
+
parser = all_parsers
|
| 753 |
+
msg = "Specified a sep and a delimiter; you can only specify one."
|
| 754 |
+
with pytest.raises(ValueError, match=msg):
|
| 755 |
+
parser.read_csv(f, sep=" ", delimiter=".")
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
@pytest.mark.parametrize("kwargs", [{"delimiter": "\n"}, {"sep": "\n"}])
|
| 759 |
+
def test_read_csv_line_break_as_separator(kwargs, all_parsers):
|
| 760 |
+
# GH#43528
|
| 761 |
+
parser = all_parsers
|
| 762 |
+
data = """a,b,c
|
| 763 |
+
1,2,3
|
| 764 |
+
"""
|
| 765 |
+
msg = (
|
| 766 |
+
r"Specified \\n as separator or delimiter. This forces the python engine "
|
| 767 |
+
r"which does not accept a line terminator. Hence it is not allowed to use "
|
| 768 |
+
r"the line terminator as separator."
|
| 769 |
+
)
|
| 770 |
+
with pytest.raises(ValueError, match=msg):
|
| 771 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
@pytest.mark.parametrize("delimiter", [",", "\t"])
|
| 775 |
+
def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter):
|
| 776 |
+
# GH: 35958
|
| 777 |
+
f = StringIO("a b c\n1 -2 -3\n4 5 6")
|
| 778 |
+
parser = all_parsers
|
| 779 |
+
msg = (
|
| 780 |
+
"Specified a delimiter with both sep and "
|
| 781 |
+
"delim_whitespace=True; you can only specify one."
|
| 782 |
+
)
|
| 783 |
+
with pytest.raises(ValueError, match=msg):
|
| 784 |
+
parser.read_table(f, delim_whitespace=True, sep=delimiter)
|
| 785 |
+
|
| 786 |
+
with pytest.raises(ValueError, match=msg):
|
| 787 |
+
parser.read_table(f, delim_whitespace=True, delimiter=delimiter)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@xfail_pyarrow
|
| 791 |
+
def test_dict_keys_as_names(all_parsers):
|
| 792 |
+
# GH: 36928
|
| 793 |
+
data = "1,2"
|
| 794 |
+
|
| 795 |
+
keys = {"a": int, "b": int}.keys()
|
| 796 |
+
parser = all_parsers
|
| 797 |
+
|
| 798 |
+
result = parser.read_csv(StringIO(data), names=keys)
|
| 799 |
+
expected = DataFrame({"a": [1], "b": [2]})
|
| 800 |
+
tm.assert_frame_equal(result, expected)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
@xfail_pyarrow
|
| 804 |
+
def test_encoding_surrogatepass(all_parsers):
|
| 805 |
+
# GH39017
|
| 806 |
+
parser = all_parsers
|
| 807 |
+
content = b"\xed\xbd\xbf"
|
| 808 |
+
decoded = content.decode("utf-8", errors="surrogatepass")
|
| 809 |
+
expected = DataFrame({decoded: [decoded]}, index=[decoded * 2])
|
| 810 |
+
expected.index.name = decoded * 2
|
| 811 |
+
|
| 812 |
+
with tm.ensure_clean() as path:
|
| 813 |
+
Path(path).write_bytes(
|
| 814 |
+
content * 2 + b"," + content + b"\n" + content * 2 + b"," + content
|
| 815 |
+
)
|
| 816 |
+
df = parser.read_csv(path, encoding_errors="surrogatepass", index_col=0)
|
| 817 |
+
tm.assert_frame_equal(df, expected)
|
| 818 |
+
with pytest.raises(UnicodeDecodeError, match="'utf-8' codec can't decode byte"):
|
| 819 |
+
parser.read_csv(path)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def test_malformed_second_line(all_parsers):
|
| 823 |
+
# see GH14782
|
| 824 |
+
parser = all_parsers
|
| 825 |
+
data = "\na\nb\n"
|
| 826 |
+
result = parser.read_csv(StringIO(data), skip_blank_lines=False, header=1)
|
| 827 |
+
expected = DataFrame({"a": ["b"]})
|
| 828 |
+
tm.assert_frame_equal(result, expected)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@xfail_pyarrow
|
| 832 |
+
def test_short_single_line(all_parsers):
|
| 833 |
+
# GH 47566
|
| 834 |
+
parser = all_parsers
|
| 835 |
+
columns = ["a", "b", "c"]
|
| 836 |
+
data = "1,2"
|
| 837 |
+
result = parser.read_csv(StringIO(data), header=None, names=columns)
|
| 838 |
+
expected = DataFrame({"a": [1], "b": [2], "c": [np.nan]})
|
| 839 |
+
tm.assert_frame_equal(result, expected)
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
@xfail_pyarrow
|
| 843 |
+
def test_short_multi_line(all_parsers):
|
| 844 |
+
# GH 47566
|
| 845 |
+
parser = all_parsers
|
| 846 |
+
columns = ["a", "b", "c"]
|
| 847 |
+
data = "1,2\n1,2"
|
| 848 |
+
result = parser.read_csv(StringIO(data), header=None, names=columns)
|
| 849 |
+
expected = DataFrame({"a": [1, 1], "b": [2, 2], "c": [np.nan, np.nan]})
|
| 850 |
+
tm.assert_frame_equal(result, expected)
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def test_read_seek(all_parsers):
|
| 854 |
+
# GH48646
|
| 855 |
+
parser = all_parsers
|
| 856 |
+
prefix = "### DATA\n"
|
| 857 |
+
content = "nkey,value\ntables,rectangular\n"
|
| 858 |
+
with tm.ensure_clean() as path:
|
| 859 |
+
Path(path).write_text(prefix + content)
|
| 860 |
+
with open(path, encoding="utf-8") as file:
|
| 861 |
+
file.readline()
|
| 862 |
+
actual = parser.read_csv(file)
|
| 863 |
+
expected = parser.read_csv(StringIO(content))
|
| 864 |
+
tm.assert_frame_equal(actual, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_data_list.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
import csv
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from pandas import DataFrame
|
| 11 |
+
import pandas._testing as tm
|
| 12 |
+
|
| 13 |
+
from pandas.io.parsers import TextParser
|
| 14 |
+
|
| 15 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@xfail_pyarrow
|
| 19 |
+
def test_read_data_list(all_parsers):
|
| 20 |
+
parser = all_parsers
|
| 21 |
+
kwargs = {"index_col": 0}
|
| 22 |
+
data = "A,B,C\nfoo,1,2,3\nbar,4,5,6"
|
| 23 |
+
|
| 24 |
+
data_list = [["A", "B", "C"], ["foo", "1", "2", "3"], ["bar", "4", "5", "6"]]
|
| 25 |
+
expected = parser.read_csv(StringIO(data), **kwargs)
|
| 26 |
+
|
| 27 |
+
with TextParser(data_list, chunksize=2, **kwargs) as parser:
|
| 28 |
+
result = parser.read()
|
| 29 |
+
|
| 30 |
+
tm.assert_frame_equal(result, expected)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_reader_list(all_parsers):
|
| 34 |
+
data = """index,A,B,C,D
|
| 35 |
+
foo,2,3,4,5
|
| 36 |
+
bar,7,8,9,10
|
| 37 |
+
baz,12,13,14,15
|
| 38 |
+
qux,12,13,14,15
|
| 39 |
+
foo2,12,13,14,15
|
| 40 |
+
bar2,12,13,14,15
|
| 41 |
+
"""
|
| 42 |
+
parser = all_parsers
|
| 43 |
+
kwargs = {"index_col": 0}
|
| 44 |
+
|
| 45 |
+
lines = list(csv.reader(StringIO(data)))
|
| 46 |
+
with TextParser(lines, chunksize=2, **kwargs) as reader:
|
| 47 |
+
chunks = list(reader)
|
| 48 |
+
|
| 49 |
+
expected = parser.read_csv(StringIO(data), **kwargs)
|
| 50 |
+
|
| 51 |
+
tm.assert_frame_equal(chunks[0], expected[:2])
|
| 52 |
+
tm.assert_frame_equal(chunks[1], expected[2:4])
|
| 53 |
+
tm.assert_frame_equal(chunks[2], expected[4:])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_reader_list_skiprows(all_parsers):
|
| 57 |
+
data = """index,A,B,C,D
|
| 58 |
+
foo,2,3,4,5
|
| 59 |
+
bar,7,8,9,10
|
| 60 |
+
baz,12,13,14,15
|
| 61 |
+
qux,12,13,14,15
|
| 62 |
+
foo2,12,13,14,15
|
| 63 |
+
bar2,12,13,14,15
|
| 64 |
+
"""
|
| 65 |
+
parser = all_parsers
|
| 66 |
+
kwargs = {"index_col": 0}
|
| 67 |
+
|
| 68 |
+
lines = list(csv.reader(StringIO(data)))
|
| 69 |
+
with TextParser(lines, chunksize=2, skiprows=[1], **kwargs) as reader:
|
| 70 |
+
chunks = list(reader)
|
| 71 |
+
|
| 72 |
+
expected = parser.read_csv(StringIO(data), **kwargs)
|
| 73 |
+
|
| 74 |
+
tm.assert_frame_equal(chunks[0], expected[1:3])
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_read_csv_parse_simple_list(all_parsers):
|
| 78 |
+
parser = all_parsers
|
| 79 |
+
data = """foo
|
| 80 |
+
bar baz
|
| 81 |
+
qux foo
|
| 82 |
+
foo
|
| 83 |
+
bar"""
|
| 84 |
+
|
| 85 |
+
result = parser.read_csv(StringIO(data), header=None)
|
| 86 |
+
expected = DataFrame(["foo", "bar baz", "qux foo", "foo", "bar"])
|
| 87 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_decimal.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
from io import StringIO
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas import DataFrame
|
| 10 |
+
import pandas._testing as tm
|
| 11 |
+
|
| 12 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@xfail_pyarrow
|
| 16 |
+
@pytest.mark.parametrize(
|
| 17 |
+
"data,thousands,decimal",
|
| 18 |
+
[
|
| 19 |
+
(
|
| 20 |
+
"""A|B|C
|
| 21 |
+
1|2,334.01|5
|
| 22 |
+
10|13|10.
|
| 23 |
+
""",
|
| 24 |
+
",",
|
| 25 |
+
".",
|
| 26 |
+
),
|
| 27 |
+
(
|
| 28 |
+
"""A|B|C
|
| 29 |
+
1|2.334,01|5
|
| 30 |
+
10|13|10,
|
| 31 |
+
""",
|
| 32 |
+
".",
|
| 33 |
+
",",
|
| 34 |
+
),
|
| 35 |
+
],
|
| 36 |
+
)
|
| 37 |
+
def test_1000_sep_with_decimal(all_parsers, data, thousands, decimal):
|
| 38 |
+
parser = all_parsers
|
| 39 |
+
expected = DataFrame({"A": [1, 10], "B": [2334.01, 13], "C": [5, 10.0]})
|
| 40 |
+
|
| 41 |
+
result = parser.read_csv(
|
| 42 |
+
StringIO(data), sep="|", thousands=thousands, decimal=decimal
|
| 43 |
+
)
|
| 44 |
+
tm.assert_frame_equal(result, expected)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_euro_decimal_format(all_parsers):
|
| 48 |
+
parser = all_parsers
|
| 49 |
+
data = """Id;Number1;Number2;Text1;Text2;Number3
|
| 50 |
+
1;1521,1541;187101,9543;ABC;poi;4,738797819
|
| 51 |
+
2;121,12;14897,76;DEF;uyt;0,377320872
|
| 52 |
+
3;878,158;108013,434;GHI;rez;2,735694704"""
|
| 53 |
+
|
| 54 |
+
result = parser.read_csv(StringIO(data), sep=";", decimal=",")
|
| 55 |
+
expected = DataFrame(
|
| 56 |
+
[
|
| 57 |
+
[1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819],
|
| 58 |
+
[2, 121.12, 14897.76, "DEF", "uyt", 0.377320872],
|
| 59 |
+
[3, 878.158, 108013.434, "GHI", "rez", 2.735694704],
|
| 60 |
+
],
|
| 61 |
+
columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"],
|
| 62 |
+
)
|
| 63 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_file_buffer_url.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 5 |
+
from io import (
|
| 6 |
+
BytesIO,
|
| 7 |
+
StringIO,
|
| 8 |
+
)
|
| 9 |
+
import os
|
| 10 |
+
import platform
|
| 11 |
+
from urllib.error import URLError
|
| 12 |
+
import uuid
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
from pandas.errors import (
|
| 17 |
+
EmptyDataError,
|
| 18 |
+
ParserError,
|
| 19 |
+
)
|
| 20 |
+
import pandas.util._test_decorators as td
|
| 21 |
+
|
| 22 |
+
from pandas import DataFrame
|
| 23 |
+
import pandas._testing as tm
|
| 24 |
+
|
| 25 |
+
# TODO(1.4) Please xfail individual tests at release time
|
| 26 |
+
# instead of skip
|
| 27 |
+
pytestmark = pytest.mark.usefixtures("pyarrow_skip")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.mark.network
|
| 31 |
+
@tm.network(
|
| 32 |
+
url=(
|
| 33 |
+
"https://raw.githubusercontent.com/pandas-dev/pandas/main/"
|
| 34 |
+
"pandas/tests/io/parser/data/salaries.csv"
|
| 35 |
+
),
|
| 36 |
+
check_before_test=True,
|
| 37 |
+
)
|
| 38 |
+
def test_url(all_parsers, csv_dir_path):
|
| 39 |
+
parser = all_parsers
|
| 40 |
+
kwargs = {"sep": "\t"}
|
| 41 |
+
|
| 42 |
+
url = (
|
| 43 |
+
"https://raw.githubusercontent.com/pandas-dev/pandas/main/"
|
| 44 |
+
"pandas/tests/io/parser/data/salaries.csv"
|
| 45 |
+
)
|
| 46 |
+
url_result = parser.read_csv(url, **kwargs)
|
| 47 |
+
|
| 48 |
+
local_path = os.path.join(csv_dir_path, "salaries.csv")
|
| 49 |
+
local_result = parser.read_csv(local_path, **kwargs)
|
| 50 |
+
tm.assert_frame_equal(url_result, local_result)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@pytest.mark.slow
|
| 54 |
+
def test_local_file(all_parsers, csv_dir_path):
|
| 55 |
+
parser = all_parsers
|
| 56 |
+
kwargs = {"sep": "\t"}
|
| 57 |
+
|
| 58 |
+
local_path = os.path.join(csv_dir_path, "salaries.csv")
|
| 59 |
+
local_result = parser.read_csv(local_path, **kwargs)
|
| 60 |
+
url = "file://localhost/" + local_path
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
url_result = parser.read_csv(url, **kwargs)
|
| 64 |
+
tm.assert_frame_equal(url_result, local_result)
|
| 65 |
+
except URLError:
|
| 66 |
+
# Fails on some systems.
|
| 67 |
+
pytest.skip("Failing on: " + " ".join(platform.uname()))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_path_path_lib(all_parsers):
|
| 71 |
+
parser = all_parsers
|
| 72 |
+
df = tm.makeDataFrame()
|
| 73 |
+
result = tm.round_trip_pathlib(df.to_csv, lambda p: parser.read_csv(p, index_col=0))
|
| 74 |
+
tm.assert_frame_equal(df, result)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_path_local_path(all_parsers):
|
| 78 |
+
parser = all_parsers
|
| 79 |
+
df = tm.makeDataFrame()
|
| 80 |
+
result = tm.round_trip_localpath(
|
| 81 |
+
df.to_csv, lambda p: parser.read_csv(p, index_col=0)
|
| 82 |
+
)
|
| 83 |
+
tm.assert_frame_equal(df, result)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_nonexistent_path(all_parsers):
|
| 87 |
+
# gh-2428: pls no segfault
|
| 88 |
+
# gh-14086: raise more helpful FileNotFoundError
|
| 89 |
+
# GH#29233 "File foo" instead of "File b'foo'"
|
| 90 |
+
parser = all_parsers
|
| 91 |
+
path = f"{uuid.uuid4()}.csv"
|
| 92 |
+
|
| 93 |
+
msg = r"\[Errno 2\]"
|
| 94 |
+
with pytest.raises(FileNotFoundError, match=msg) as e:
|
| 95 |
+
parser.read_csv(path)
|
| 96 |
+
assert path == e.value.filename
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@td.skip_if_windows # os.chmod does not work in windows
|
| 100 |
+
def test_no_permission(all_parsers):
|
| 101 |
+
# GH 23784
|
| 102 |
+
parser = all_parsers
|
| 103 |
+
|
| 104 |
+
msg = r"\[Errno 13\]"
|
| 105 |
+
with tm.ensure_clean() as path:
|
| 106 |
+
os.chmod(path, 0) # make file unreadable
|
| 107 |
+
|
| 108 |
+
# verify that this process cannot open the file (not running as sudo)
|
| 109 |
+
try:
|
| 110 |
+
with open(path):
|
| 111 |
+
pass
|
| 112 |
+
pytest.skip("Running as sudo.")
|
| 113 |
+
except PermissionError:
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
with pytest.raises(PermissionError, match=msg) as e:
|
| 117 |
+
parser.read_csv(path)
|
| 118 |
+
assert path == e.value.filename
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize(
|
| 122 |
+
"data,kwargs,expected,msg",
|
| 123 |
+
[
|
| 124 |
+
# gh-10728: WHITESPACE_LINE
|
| 125 |
+
(
|
| 126 |
+
"a,b,c\n4,5,6\n ",
|
| 127 |
+
{},
|
| 128 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 129 |
+
None,
|
| 130 |
+
),
|
| 131 |
+
# gh-10548: EAT_LINE_COMMENT
|
| 132 |
+
(
|
| 133 |
+
"a,b,c\n4,5,6\n#comment",
|
| 134 |
+
{"comment": "#"},
|
| 135 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 136 |
+
None,
|
| 137 |
+
),
|
| 138 |
+
# EAT_CRNL_NOP
|
| 139 |
+
(
|
| 140 |
+
"a,b,c\n4,5,6\n\r",
|
| 141 |
+
{},
|
| 142 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 143 |
+
None,
|
| 144 |
+
),
|
| 145 |
+
# EAT_COMMENT
|
| 146 |
+
(
|
| 147 |
+
"a,b,c\n4,5,6#comment",
|
| 148 |
+
{"comment": "#"},
|
| 149 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 150 |
+
None,
|
| 151 |
+
),
|
| 152 |
+
# SKIP_LINE
|
| 153 |
+
(
|
| 154 |
+
"a,b,c\n4,5,6\nskipme",
|
| 155 |
+
{"skiprows": [2]},
|
| 156 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 157 |
+
None,
|
| 158 |
+
),
|
| 159 |
+
# EAT_LINE_COMMENT
|
| 160 |
+
(
|
| 161 |
+
"a,b,c\n4,5,6\n#comment",
|
| 162 |
+
{"comment": "#", "skip_blank_lines": False},
|
| 163 |
+
DataFrame([[4, 5, 6]], columns=["a", "b", "c"]),
|
| 164 |
+
None,
|
| 165 |
+
),
|
| 166 |
+
# IN_FIELD
|
| 167 |
+
(
|
| 168 |
+
"a,b,c\n4,5,6\n ",
|
| 169 |
+
{"skip_blank_lines": False},
|
| 170 |
+
DataFrame([["4", 5, 6], [" ", None, None]], columns=["a", "b", "c"]),
|
| 171 |
+
None,
|
| 172 |
+
),
|
| 173 |
+
# EAT_CRNL
|
| 174 |
+
(
|
| 175 |
+
"a,b,c\n4,5,6\n\r",
|
| 176 |
+
{"skip_blank_lines": False},
|
| 177 |
+
DataFrame([[4, 5, 6], [None, None, None]], columns=["a", "b", "c"]),
|
| 178 |
+
None,
|
| 179 |
+
),
|
| 180 |
+
# ESCAPED_CHAR
|
| 181 |
+
(
|
| 182 |
+
"a,b,c\n4,5,6\n\\",
|
| 183 |
+
{"escapechar": "\\"},
|
| 184 |
+
None,
|
| 185 |
+
"(EOF following escape character)|(unexpected end of data)",
|
| 186 |
+
),
|
| 187 |
+
# ESCAPE_IN_QUOTED_FIELD
|
| 188 |
+
(
|
| 189 |
+
'a,b,c\n4,5,6\n"\\',
|
| 190 |
+
{"escapechar": "\\"},
|
| 191 |
+
None,
|
| 192 |
+
"(EOF inside string starting at row 2)|(unexpected end of data)",
|
| 193 |
+
),
|
| 194 |
+
# IN_QUOTED_FIELD
|
| 195 |
+
(
|
| 196 |
+
'a,b,c\n4,5,6\n"',
|
| 197 |
+
{"escapechar": "\\"},
|
| 198 |
+
None,
|
| 199 |
+
"(EOF inside string starting at row 2)|(unexpected end of data)",
|
| 200 |
+
),
|
| 201 |
+
],
|
| 202 |
+
ids=[
|
| 203 |
+
"whitespace-line",
|
| 204 |
+
"eat-line-comment",
|
| 205 |
+
"eat-crnl-nop",
|
| 206 |
+
"eat-comment",
|
| 207 |
+
"skip-line",
|
| 208 |
+
"eat-line-comment",
|
| 209 |
+
"in-field",
|
| 210 |
+
"eat-crnl",
|
| 211 |
+
"escaped-char",
|
| 212 |
+
"escape-in-quoted-field",
|
| 213 |
+
"in-quoted-field",
|
| 214 |
+
],
|
| 215 |
+
)
|
| 216 |
+
def test_eof_states(all_parsers, data, kwargs, expected, msg):
|
| 217 |
+
# see gh-10728, gh-10548
|
| 218 |
+
parser = all_parsers
|
| 219 |
+
|
| 220 |
+
if expected is None:
|
| 221 |
+
with pytest.raises(ParserError, match=msg):
|
| 222 |
+
parser.read_csv(StringIO(data), **kwargs)
|
| 223 |
+
else:
|
| 224 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 225 |
+
tm.assert_frame_equal(result, expected)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def test_temporary_file(all_parsers):
|
| 229 |
+
# see gh-13398
|
| 230 |
+
parser = all_parsers
|
| 231 |
+
data = "0 0"
|
| 232 |
+
|
| 233 |
+
with tm.ensure_clean(mode="w+", return_filelike=True) as new_file:
|
| 234 |
+
new_file.write(data)
|
| 235 |
+
new_file.flush()
|
| 236 |
+
new_file.seek(0)
|
| 237 |
+
|
| 238 |
+
result = parser.read_csv(new_file, sep=r"\s+", header=None)
|
| 239 |
+
|
| 240 |
+
expected = DataFrame([[0, 0]])
|
| 241 |
+
tm.assert_frame_equal(result, expected)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def test_internal_eof_byte(all_parsers):
|
| 245 |
+
# see gh-5500
|
| 246 |
+
parser = all_parsers
|
| 247 |
+
data = "a,b\n1\x1a,2"
|
| 248 |
+
|
| 249 |
+
expected = DataFrame([["1\x1a", 2]], columns=["a", "b"])
|
| 250 |
+
result = parser.read_csv(StringIO(data))
|
| 251 |
+
tm.assert_frame_equal(result, expected)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_internal_eof_byte_to_file(all_parsers):
|
| 255 |
+
# see gh-16559
|
| 256 |
+
parser = all_parsers
|
| 257 |
+
data = b'c1,c2\r\n"test \x1a test", test\r\n'
|
| 258 |
+
expected = DataFrame([["test \x1a test", " test"]], columns=["c1", "c2"])
|
| 259 |
+
path = f"__{uuid.uuid4()}__.csv"
|
| 260 |
+
|
| 261 |
+
with tm.ensure_clean(path) as path:
|
| 262 |
+
with open(path, "wb") as f:
|
| 263 |
+
f.write(data)
|
| 264 |
+
|
| 265 |
+
result = parser.read_csv(path)
|
| 266 |
+
tm.assert_frame_equal(result, expected)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def test_file_handle_string_io(all_parsers):
|
| 270 |
+
# gh-14418
|
| 271 |
+
#
|
| 272 |
+
# Don't close user provided file handles.
|
| 273 |
+
parser = all_parsers
|
| 274 |
+
data = "a,b\n1,2"
|
| 275 |
+
|
| 276 |
+
fh = StringIO(data)
|
| 277 |
+
parser.read_csv(fh)
|
| 278 |
+
assert not fh.closed
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def test_file_handles_with_open(all_parsers, csv1):
|
| 282 |
+
# gh-14418
|
| 283 |
+
#
|
| 284 |
+
# Don't close user provided file handles.
|
| 285 |
+
parser = all_parsers
|
| 286 |
+
|
| 287 |
+
for mode in ["r", "rb"]:
|
| 288 |
+
with open(csv1, mode) as f:
|
| 289 |
+
parser.read_csv(f)
|
| 290 |
+
assert not f.closed
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_invalid_file_buffer_class(all_parsers):
|
| 294 |
+
# see gh-15337
|
| 295 |
+
class InvalidBuffer:
|
| 296 |
+
pass
|
| 297 |
+
|
| 298 |
+
parser = all_parsers
|
| 299 |
+
msg = "Invalid file path or buffer object type"
|
| 300 |
+
|
| 301 |
+
with pytest.raises(ValueError, match=msg):
|
| 302 |
+
parser.read_csv(InvalidBuffer())
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def test_invalid_file_buffer_mock(all_parsers):
|
| 306 |
+
# see gh-15337
|
| 307 |
+
parser = all_parsers
|
| 308 |
+
msg = "Invalid file path or buffer object type"
|
| 309 |
+
|
| 310 |
+
class Foo:
|
| 311 |
+
pass
|
| 312 |
+
|
| 313 |
+
with pytest.raises(ValueError, match=msg):
|
| 314 |
+
parser.read_csv(Foo())
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def test_valid_file_buffer_seems_invalid(all_parsers):
|
| 318 |
+
# gh-16135: we want to ensure that "tell" and "seek"
|
| 319 |
+
# aren't actually being used when we call `read_csv`
|
| 320 |
+
#
|
| 321 |
+
# Thus, while the object may look "invalid" (these
|
| 322 |
+
# methods are attributes of the `StringIO` class),
|
| 323 |
+
# it is still a valid file-object for our purposes.
|
| 324 |
+
class NoSeekTellBuffer(StringIO):
|
| 325 |
+
def tell(self):
|
| 326 |
+
raise AttributeError("No tell method")
|
| 327 |
+
|
| 328 |
+
def seek(self, pos, whence=0):
|
| 329 |
+
raise AttributeError("No seek method")
|
| 330 |
+
|
| 331 |
+
data = "a\n1"
|
| 332 |
+
parser = all_parsers
|
| 333 |
+
expected = DataFrame({"a": [1]})
|
| 334 |
+
|
| 335 |
+
result = parser.read_csv(NoSeekTellBuffer(data))
|
| 336 |
+
tm.assert_frame_equal(result, expected)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@pytest.mark.parametrize("io_class", [StringIO, BytesIO])
|
| 340 |
+
@pytest.mark.parametrize("encoding", [None, "utf-8"])
|
| 341 |
+
def test_read_csv_file_handle(all_parsers, io_class, encoding):
|
| 342 |
+
"""
|
| 343 |
+
Test whether read_csv does not close user-provided file handles.
|
| 344 |
+
|
| 345 |
+
GH 36980
|
| 346 |
+
"""
|
| 347 |
+
parser = all_parsers
|
| 348 |
+
expected = DataFrame({"a": [1], "b": [2]})
|
| 349 |
+
|
| 350 |
+
content = "a,b\n1,2"
|
| 351 |
+
handle = io_class(content.encode("utf-8") if io_class == BytesIO else content)
|
| 352 |
+
|
| 353 |
+
tm.assert_frame_equal(parser.read_csv(handle, encoding=encoding), expected)
|
| 354 |
+
assert not handle.closed
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def test_memory_map_compression(all_parsers, compression):
|
| 358 |
+
"""
|
| 359 |
+
Support memory map for compressed files.
|
| 360 |
+
|
| 361 |
+
GH 37621
|
| 362 |
+
"""
|
| 363 |
+
parser = all_parsers
|
| 364 |
+
expected = DataFrame({"a": [1], "b": [2]})
|
| 365 |
+
|
| 366 |
+
with tm.ensure_clean() as path:
|
| 367 |
+
expected.to_csv(path, index=False, compression=compression)
|
| 368 |
+
|
| 369 |
+
tm.assert_frame_equal(
|
| 370 |
+
parser.read_csv(path, memory_map=True, compression=compression),
|
| 371 |
+
expected,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_context_manager(all_parsers, datapath):
|
| 376 |
+
# make sure that opened files are closed
|
| 377 |
+
parser = all_parsers
|
| 378 |
+
|
| 379 |
+
path = datapath("io", "data", "csv", "iris.csv")
|
| 380 |
+
|
| 381 |
+
reader = parser.read_csv(path, chunksize=1)
|
| 382 |
+
assert not reader.handles.handle.closed
|
| 383 |
+
try:
|
| 384 |
+
with reader:
|
| 385 |
+
next(reader)
|
| 386 |
+
assert False
|
| 387 |
+
except AssertionError:
|
| 388 |
+
assert reader.handles.handle.closed
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_context_manageri_user_provided(all_parsers, datapath):
|
| 392 |
+
# make sure that user-provided handles are not closed
|
| 393 |
+
parser = all_parsers
|
| 394 |
+
|
| 395 |
+
with open(datapath("io", "data", "csv", "iris.csv")) as path:
|
| 396 |
+
reader = parser.read_csv(path, chunksize=1)
|
| 397 |
+
assert not reader.handles.handle.closed
|
| 398 |
+
try:
|
| 399 |
+
with reader:
|
| 400 |
+
next(reader)
|
| 401 |
+
assert False
|
| 402 |
+
except AssertionError:
|
| 403 |
+
assert not reader.handles.handle.closed
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def test_file_descriptor_leak(all_parsers, using_copy_on_write):
|
| 407 |
+
# GH 31488
|
| 408 |
+
parser = all_parsers
|
| 409 |
+
with tm.ensure_clean() as path:
|
| 410 |
+
with pytest.raises(EmptyDataError, match="No columns to parse from file"):
|
| 411 |
+
parser.read_csv(path)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def test_memory_map(all_parsers, csv_dir_path):
|
| 415 |
+
mmap_file = os.path.join(csv_dir_path, "test_mmap.csv")
|
| 416 |
+
parser = all_parsers
|
| 417 |
+
|
| 418 |
+
expected = DataFrame(
|
| 419 |
+
{"a": [1, 2, 3], "b": ["one", "two", "three"], "c": ["I", "II", "III"]}
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
result = parser.read_csv(mmap_file, memory_map=True)
|
| 423 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_index.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from io import StringIO
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from pandas import (
|
| 12 |
+
DataFrame,
|
| 13 |
+
Index,
|
| 14 |
+
MultiIndex,
|
| 15 |
+
)
|
| 16 |
+
import pandas._testing as tm
|
| 17 |
+
|
| 18 |
+
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
|
| 19 |
+
|
| 20 |
+
# GH#43650: Some expected failures with the pyarrow engine can occasionally
|
| 21 |
+
# cause a deadlock instead, so we skip these instead of xfailing
|
| 22 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.mark.parametrize(
|
| 26 |
+
"data,kwargs,expected",
|
| 27 |
+
[
|
| 28 |
+
(
|
| 29 |
+
"""foo,2,3,4,5
|
| 30 |
+
bar,7,8,9,10
|
| 31 |
+
baz,12,13,14,15
|
| 32 |
+
qux,12,13,14,15
|
| 33 |
+
foo2,12,13,14,15
|
| 34 |
+
bar2,12,13,14,15
|
| 35 |
+
""",
|
| 36 |
+
{"index_col": 0, "names": ["index", "A", "B", "C", "D"]},
|
| 37 |
+
DataFrame(
|
| 38 |
+
[
|
| 39 |
+
[2, 3, 4, 5],
|
| 40 |
+
[7, 8, 9, 10],
|
| 41 |
+
[12, 13, 14, 15],
|
| 42 |
+
[12, 13, 14, 15],
|
| 43 |
+
[12, 13, 14, 15],
|
| 44 |
+
[12, 13, 14, 15],
|
| 45 |
+
],
|
| 46 |
+
index=Index(["foo", "bar", "baz", "qux", "foo2", "bar2"], name="index"),
|
| 47 |
+
columns=["A", "B", "C", "D"],
|
| 48 |
+
),
|
| 49 |
+
),
|
| 50 |
+
(
|
| 51 |
+
"""foo,one,2,3,4,5
|
| 52 |
+
foo,two,7,8,9,10
|
| 53 |
+
foo,three,12,13,14,15
|
| 54 |
+
bar,one,12,13,14,15
|
| 55 |
+
bar,two,12,13,14,15
|
| 56 |
+
""",
|
| 57 |
+
{"index_col": [0, 1], "names": ["index1", "index2", "A", "B", "C", "D"]},
|
| 58 |
+
DataFrame(
|
| 59 |
+
[
|
| 60 |
+
[2, 3, 4, 5],
|
| 61 |
+
[7, 8, 9, 10],
|
| 62 |
+
[12, 13, 14, 15],
|
| 63 |
+
[12, 13, 14, 15],
|
| 64 |
+
[12, 13, 14, 15],
|
| 65 |
+
],
|
| 66 |
+
index=MultiIndex.from_tuples(
|
| 67 |
+
[
|
| 68 |
+
("foo", "one"),
|
| 69 |
+
("foo", "two"),
|
| 70 |
+
("foo", "three"),
|
| 71 |
+
("bar", "one"),
|
| 72 |
+
("bar", "two"),
|
| 73 |
+
],
|
| 74 |
+
names=["index1", "index2"],
|
| 75 |
+
),
|
| 76 |
+
columns=["A", "B", "C", "D"],
|
| 77 |
+
),
|
| 78 |
+
),
|
| 79 |
+
],
|
| 80 |
+
)
|
| 81 |
+
def test_pass_names_with_index(all_parsers, data, kwargs, expected):
|
| 82 |
+
parser = all_parsers
|
| 83 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 84 |
+
tm.assert_frame_equal(result, expected)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize("index_col", [[0, 1], [1, 0]])
|
| 88 |
+
def test_multi_index_no_level_names(all_parsers, index_col):
|
| 89 |
+
data = """index1,index2,A,B,C,D
|
| 90 |
+
foo,one,2,3,4,5
|
| 91 |
+
foo,two,7,8,9,10
|
| 92 |
+
foo,three,12,13,14,15
|
| 93 |
+
bar,one,12,13,14,15
|
| 94 |
+
bar,two,12,13,14,15
|
| 95 |
+
"""
|
| 96 |
+
headless_data = "\n".join(data.split("\n")[1:])
|
| 97 |
+
|
| 98 |
+
names = ["A", "B", "C", "D"]
|
| 99 |
+
parser = all_parsers
|
| 100 |
+
|
| 101 |
+
result = parser.read_csv(
|
| 102 |
+
StringIO(headless_data), index_col=index_col, header=None, names=names
|
| 103 |
+
)
|
| 104 |
+
expected = parser.read_csv(StringIO(data), index_col=index_col)
|
| 105 |
+
|
| 106 |
+
# No index names in headless data.
|
| 107 |
+
expected.index.names = [None] * 2
|
| 108 |
+
tm.assert_frame_equal(result, expected)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@xfail_pyarrow
|
| 112 |
+
def test_multi_index_no_level_names_implicit(all_parsers):
|
| 113 |
+
parser = all_parsers
|
| 114 |
+
data = """A,B,C,D
|
| 115 |
+
foo,one,2,3,4,5
|
| 116 |
+
foo,two,7,8,9,10
|
| 117 |
+
foo,three,12,13,14,15
|
| 118 |
+
bar,one,12,13,14,15
|
| 119 |
+
bar,two,12,13,14,15
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
result = parser.read_csv(StringIO(data))
|
| 123 |
+
expected = DataFrame(
|
| 124 |
+
[
|
| 125 |
+
[2, 3, 4, 5],
|
| 126 |
+
[7, 8, 9, 10],
|
| 127 |
+
[12, 13, 14, 15],
|
| 128 |
+
[12, 13, 14, 15],
|
| 129 |
+
[12, 13, 14, 15],
|
| 130 |
+
],
|
| 131 |
+
columns=["A", "B", "C", "D"],
|
| 132 |
+
index=MultiIndex.from_tuples(
|
| 133 |
+
[
|
| 134 |
+
("foo", "one"),
|
| 135 |
+
("foo", "two"),
|
| 136 |
+
("foo", "three"),
|
| 137 |
+
("bar", "one"),
|
| 138 |
+
("bar", "two"),
|
| 139 |
+
]
|
| 140 |
+
),
|
| 141 |
+
)
|
| 142 |
+
tm.assert_frame_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@xfail_pyarrow
|
| 146 |
+
@pytest.mark.parametrize(
|
| 147 |
+
"data,expected,header",
|
| 148 |
+
[
|
| 149 |
+
("a,b", DataFrame(columns=["a", "b"]), [0]),
|
| 150 |
+
(
|
| 151 |
+
"a,b\nc,d",
|
| 152 |
+
DataFrame(columns=MultiIndex.from_tuples([("a", "c"), ("b", "d")])),
|
| 153 |
+
[0, 1],
|
| 154 |
+
),
|
| 155 |
+
],
|
| 156 |
+
)
|
| 157 |
+
@pytest.mark.parametrize("round_trip", [True, False])
|
| 158 |
+
def test_multi_index_blank_df(all_parsers, data, expected, header, round_trip):
|
| 159 |
+
# see gh-14545
|
| 160 |
+
parser = all_parsers
|
| 161 |
+
data = expected.to_csv(index=False) if round_trip else data
|
| 162 |
+
|
| 163 |
+
result = parser.read_csv(StringIO(data), header=header)
|
| 164 |
+
tm.assert_frame_equal(result, expected)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@xfail_pyarrow
|
| 168 |
+
def test_no_unnamed_index(all_parsers):
|
| 169 |
+
parser = all_parsers
|
| 170 |
+
data = """ id c0 c1 c2
|
| 171 |
+
0 1 0 a b
|
| 172 |
+
1 2 0 c d
|
| 173 |
+
2 2 2 e f
|
| 174 |
+
"""
|
| 175 |
+
result = parser.read_csv(StringIO(data), sep=" ")
|
| 176 |
+
expected = DataFrame(
|
| 177 |
+
[[0, 1, 0, "a", "b"], [1, 2, 0, "c", "d"], [2, 2, 2, "e", "f"]],
|
| 178 |
+
columns=["Unnamed: 0", "id", "c0", "c1", "c2"],
|
| 179 |
+
)
|
| 180 |
+
tm.assert_frame_equal(result, expected)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_read_duplicate_index_explicit(all_parsers):
|
| 184 |
+
data = """index,A,B,C,D
|
| 185 |
+
foo,2,3,4,5
|
| 186 |
+
bar,7,8,9,10
|
| 187 |
+
baz,12,13,14,15
|
| 188 |
+
qux,12,13,14,15
|
| 189 |
+
foo,12,13,14,15
|
| 190 |
+
bar,12,13,14,15
|
| 191 |
+
"""
|
| 192 |
+
parser = all_parsers
|
| 193 |
+
result = parser.read_csv(StringIO(data), index_col=0)
|
| 194 |
+
|
| 195 |
+
expected = DataFrame(
|
| 196 |
+
[
|
| 197 |
+
[2, 3, 4, 5],
|
| 198 |
+
[7, 8, 9, 10],
|
| 199 |
+
[12, 13, 14, 15],
|
| 200 |
+
[12, 13, 14, 15],
|
| 201 |
+
[12, 13, 14, 15],
|
| 202 |
+
[12, 13, 14, 15],
|
| 203 |
+
],
|
| 204 |
+
columns=["A", "B", "C", "D"],
|
| 205 |
+
index=Index(["foo", "bar", "baz", "qux", "foo", "bar"], name="index"),
|
| 206 |
+
)
|
| 207 |
+
tm.assert_frame_equal(result, expected)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@xfail_pyarrow
|
| 211 |
+
def test_read_duplicate_index_implicit(all_parsers):
|
| 212 |
+
data = """A,B,C,D
|
| 213 |
+
foo,2,3,4,5
|
| 214 |
+
bar,7,8,9,10
|
| 215 |
+
baz,12,13,14,15
|
| 216 |
+
qux,12,13,14,15
|
| 217 |
+
foo,12,13,14,15
|
| 218 |
+
bar,12,13,14,15
|
| 219 |
+
"""
|
| 220 |
+
parser = all_parsers
|
| 221 |
+
result = parser.read_csv(StringIO(data))
|
| 222 |
+
|
| 223 |
+
expected = DataFrame(
|
| 224 |
+
[
|
| 225 |
+
[2, 3, 4, 5],
|
| 226 |
+
[7, 8, 9, 10],
|
| 227 |
+
[12, 13, 14, 15],
|
| 228 |
+
[12, 13, 14, 15],
|
| 229 |
+
[12, 13, 14, 15],
|
| 230 |
+
[12, 13, 14, 15],
|
| 231 |
+
],
|
| 232 |
+
columns=["A", "B", "C", "D"],
|
| 233 |
+
index=Index(["foo", "bar", "baz", "qux", "foo", "bar"]),
|
| 234 |
+
)
|
| 235 |
+
tm.assert_frame_equal(result, expected)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@xfail_pyarrow
|
| 239 |
+
def test_read_csv_no_index_name(all_parsers, csv_dir_path):
|
| 240 |
+
parser = all_parsers
|
| 241 |
+
csv2 = os.path.join(csv_dir_path, "test2.csv")
|
| 242 |
+
result = parser.read_csv(csv2, index_col=0, parse_dates=True)
|
| 243 |
+
|
| 244 |
+
expected = DataFrame(
|
| 245 |
+
[
|
| 246 |
+
[0.980269, 3.685731, -0.364216805298, -1.159738, "foo"],
|
| 247 |
+
[1.047916, -0.041232, -0.16181208307, 0.212549, "bar"],
|
| 248 |
+
[0.498581, 0.731168, -0.537677223318, 1.346270, "baz"],
|
| 249 |
+
[1.120202, 1.567621, 0.00364077397681, 0.675253, "qux"],
|
| 250 |
+
[-0.487094, 0.571455, -1.6116394093, 0.103469, "foo2"],
|
| 251 |
+
],
|
| 252 |
+
columns=["A", "B", "C", "D", "E"],
|
| 253 |
+
index=Index(
|
| 254 |
+
[
|
| 255 |
+
datetime(2000, 1, 3),
|
| 256 |
+
datetime(2000, 1, 4),
|
| 257 |
+
datetime(2000, 1, 5),
|
| 258 |
+
datetime(2000, 1, 6),
|
| 259 |
+
datetime(2000, 1, 7),
|
| 260 |
+
]
|
| 261 |
+
),
|
| 262 |
+
)
|
| 263 |
+
tm.assert_frame_equal(result, expected)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@xfail_pyarrow
|
| 267 |
+
def test_empty_with_index(all_parsers):
|
| 268 |
+
# see gh-10184
|
| 269 |
+
data = "x,y"
|
| 270 |
+
parser = all_parsers
|
| 271 |
+
result = parser.read_csv(StringIO(data), index_col=0)
|
| 272 |
+
|
| 273 |
+
expected = DataFrame(columns=["y"], index=Index([], name="x"))
|
| 274 |
+
tm.assert_frame_equal(result, expected)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@skip_pyarrow
|
| 278 |
+
def test_empty_with_multi_index(all_parsers):
|
| 279 |
+
# see gh-10467
|
| 280 |
+
data = "x,y,z"
|
| 281 |
+
parser = all_parsers
|
| 282 |
+
result = parser.read_csv(StringIO(data), index_col=["x", "y"])
|
| 283 |
+
|
| 284 |
+
expected = DataFrame(
|
| 285 |
+
columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["x", "y"])
|
| 286 |
+
)
|
| 287 |
+
tm.assert_frame_equal(result, expected)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@skip_pyarrow
|
| 291 |
+
def test_empty_with_reversed_multi_index(all_parsers):
|
| 292 |
+
data = "x,y,z"
|
| 293 |
+
parser = all_parsers
|
| 294 |
+
result = parser.read_csv(StringIO(data), index_col=[1, 0])
|
| 295 |
+
|
| 296 |
+
expected = DataFrame(
|
| 297 |
+
columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["y", "x"])
|
| 298 |
+
)
|
| 299 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_ints.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
"""
|
| 5 |
+
from io import StringIO
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from pandas import (
|
| 11 |
+
DataFrame,
|
| 12 |
+
Series,
|
| 13 |
+
)
|
| 14 |
+
import pandas._testing as tm
|
| 15 |
+
|
| 16 |
+
# GH#43650: Some expected failures with the pyarrow engine can occasionally
|
| 17 |
+
# cause a deadlock instead, so we skip these instead of xfailing
|
| 18 |
+
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_int_conversion(all_parsers):
|
| 22 |
+
data = """A,B
|
| 23 |
+
1.0,1
|
| 24 |
+
2.0,2
|
| 25 |
+
3.0,3
|
| 26 |
+
"""
|
| 27 |
+
parser = all_parsers
|
| 28 |
+
result = parser.read_csv(StringIO(data))
|
| 29 |
+
|
| 30 |
+
expected = DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]], columns=["A", "B"])
|
| 31 |
+
tm.assert_frame_equal(result, expected)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize(
|
| 35 |
+
"data,kwargs,expected",
|
| 36 |
+
[
|
| 37 |
+
(
|
| 38 |
+
"A,B\nTrue,1\nFalse,2\nTrue,3",
|
| 39 |
+
{},
|
| 40 |
+
DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]),
|
| 41 |
+
),
|
| 42 |
+
(
|
| 43 |
+
"A,B\nYES,1\nno,2\nyes,3\nNo,3\nYes,3",
|
| 44 |
+
{"true_values": ["yes", "Yes", "YES"], "false_values": ["no", "NO", "No"]},
|
| 45 |
+
DataFrame(
|
| 46 |
+
[[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]],
|
| 47 |
+
columns=["A", "B"],
|
| 48 |
+
),
|
| 49 |
+
),
|
| 50 |
+
(
|
| 51 |
+
"A,B\nTRUE,1\nFALSE,2\nTRUE,3",
|
| 52 |
+
{},
|
| 53 |
+
DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]),
|
| 54 |
+
),
|
| 55 |
+
(
|
| 56 |
+
"A,B\nfoo,bar\nbar,foo",
|
| 57 |
+
{"true_values": ["foo"], "false_values": ["bar"]},
|
| 58 |
+
DataFrame([[True, False], [False, True]], columns=["A", "B"]),
|
| 59 |
+
),
|
| 60 |
+
],
|
| 61 |
+
)
|
| 62 |
+
def test_parse_bool(all_parsers, data, kwargs, expected):
|
| 63 |
+
parser = all_parsers
|
| 64 |
+
result = parser.read_csv(StringIO(data), **kwargs)
|
| 65 |
+
tm.assert_frame_equal(result, expected)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_parse_integers_above_fp_precision(all_parsers):
|
| 69 |
+
data = """Numbers
|
| 70 |
+
17007000002000191
|
| 71 |
+
17007000002000191
|
| 72 |
+
17007000002000191
|
| 73 |
+
17007000002000191
|
| 74 |
+
17007000002000192
|
| 75 |
+
17007000002000192
|
| 76 |
+
17007000002000192
|
| 77 |
+
17007000002000192
|
| 78 |
+
17007000002000192
|
| 79 |
+
17007000002000194"""
|
| 80 |
+
parser = all_parsers
|
| 81 |
+
result = parser.read_csv(StringIO(data))
|
| 82 |
+
expected = DataFrame(
|
| 83 |
+
{
|
| 84 |
+
"Numbers": [
|
| 85 |
+
17007000002000191,
|
| 86 |
+
17007000002000191,
|
| 87 |
+
17007000002000191,
|
| 88 |
+
17007000002000191,
|
| 89 |
+
17007000002000192,
|
| 90 |
+
17007000002000192,
|
| 91 |
+
17007000002000192,
|
| 92 |
+
17007000002000192,
|
| 93 |
+
17007000002000192,
|
| 94 |
+
17007000002000194,
|
| 95 |
+
]
|
| 96 |
+
}
|
| 97 |
+
)
|
| 98 |
+
tm.assert_frame_equal(result, expected)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@skip_pyarrow # Flaky
|
| 102 |
+
@pytest.mark.parametrize("sep", [" ", r"\s+"])
|
| 103 |
+
def test_integer_overflow_bug(all_parsers, sep):
|
| 104 |
+
# see gh-2601
|
| 105 |
+
data = "65248E10 11\n55555E55 22\n"
|
| 106 |
+
parser = all_parsers
|
| 107 |
+
|
| 108 |
+
result = parser.read_csv(StringIO(data), header=None, sep=sep)
|
| 109 |
+
expected = DataFrame([[6.5248e14, 11], [5.5555e59, 22]])
|
| 110 |
+
tm.assert_frame_equal(result, expected)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_int64_min_issues(all_parsers):
|
| 114 |
+
# see gh-2599
|
| 115 |
+
parser = all_parsers
|
| 116 |
+
data = "A,B\n0,0\n0,"
|
| 117 |
+
result = parser.read_csv(StringIO(data))
|
| 118 |
+
|
| 119 |
+
expected = DataFrame({"A": [0, 0], "B": [0, np.nan]})
|
| 120 |
+
tm.assert_frame_equal(result, expected)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@skip_pyarrow
|
| 124 |
+
@pytest.mark.parametrize("conv", [None, np.int64, np.uint64])
|
| 125 |
+
def test_int64_overflow(all_parsers, conv):
|
| 126 |
+
data = """ID
|
| 127 |
+
00013007854817840016671868
|
| 128 |
+
00013007854817840016749251
|
| 129 |
+
00013007854817840016754630
|
| 130 |
+
00013007854817840016781876
|
| 131 |
+
00013007854817840017028824
|
| 132 |
+
00013007854817840017963235
|
| 133 |
+
00013007854817840018860166"""
|
| 134 |
+
parser = all_parsers
|
| 135 |
+
|
| 136 |
+
if conv is None:
|
| 137 |
+
# 13007854817840016671868 > UINT64_MAX, so this
|
| 138 |
+
# will overflow and return object as the dtype.
|
| 139 |
+
result = parser.read_csv(StringIO(data))
|
| 140 |
+
expected = DataFrame(
|
| 141 |
+
[
|
| 142 |
+
"00013007854817840016671868",
|
| 143 |
+
"00013007854817840016749251",
|
| 144 |
+
"00013007854817840016754630",
|
| 145 |
+
"00013007854817840016781876",
|
| 146 |
+
"00013007854817840017028824",
|
| 147 |
+
"00013007854817840017963235",
|
| 148 |
+
"00013007854817840018860166",
|
| 149 |
+
],
|
| 150 |
+
columns=["ID"],
|
| 151 |
+
)
|
| 152 |
+
tm.assert_frame_equal(result, expected)
|
| 153 |
+
else:
|
| 154 |
+
# 13007854817840016671868 > UINT64_MAX, so attempts
|
| 155 |
+
# to cast to either int64 or uint64 will result in
|
| 156 |
+
# an OverflowError being raised.
|
| 157 |
+
msg = (
|
| 158 |
+
"(Python int too large to convert to C long)|"
|
| 159 |
+
"(long too big to convert)|"
|
| 160 |
+
"(int too big to convert)"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
with pytest.raises(OverflowError, match=msg):
|
| 164 |
+
parser.read_csv(StringIO(data), converters={"ID": conv})
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@skip_pyarrow
|
| 168 |
+
@pytest.mark.parametrize(
|
| 169 |
+
"val", [np.iinfo(np.uint64).max, np.iinfo(np.int64).max, np.iinfo(np.int64).min]
|
| 170 |
+
)
|
| 171 |
+
def test_int64_uint64_range(all_parsers, val):
|
| 172 |
+
# These numbers fall right inside the int64-uint64
|
| 173 |
+
# range, so they should be parsed as string.
|
| 174 |
+
parser = all_parsers
|
| 175 |
+
result = parser.read_csv(StringIO(str(val)), header=None)
|
| 176 |
+
|
| 177 |
+
expected = DataFrame([val])
|
| 178 |
+
tm.assert_frame_equal(result, expected)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@skip_pyarrow
|
| 182 |
+
@pytest.mark.parametrize(
|
| 183 |
+
"val", [np.iinfo(np.uint64).max + 1, np.iinfo(np.int64).min - 1]
|
| 184 |
+
)
|
| 185 |
+
def test_outside_int64_uint64_range(all_parsers, val):
|
| 186 |
+
# These numbers fall just outside the int64-uint64
|
| 187 |
+
# range, so they should be parsed as string.
|
| 188 |
+
parser = all_parsers
|
| 189 |
+
result = parser.read_csv(StringIO(str(val)), header=None)
|
| 190 |
+
|
| 191 |
+
expected = DataFrame([str(val)])
|
| 192 |
+
tm.assert_frame_equal(result, expected)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@skip_pyarrow
|
| 196 |
+
@pytest.mark.parametrize("exp_data", [[str(-1), str(2**63)], [str(2**63), str(-1)]])
|
| 197 |
+
def test_numeric_range_too_wide(all_parsers, exp_data):
|
| 198 |
+
# No numerical dtype can hold both negative and uint64
|
| 199 |
+
# values, so they should be cast as string.
|
| 200 |
+
parser = all_parsers
|
| 201 |
+
data = "\n".join(exp_data)
|
| 202 |
+
expected = DataFrame(exp_data)
|
| 203 |
+
|
| 204 |
+
result = parser.read_csv(StringIO(data), header=None)
|
| 205 |
+
tm.assert_frame_equal(result, expected)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def test_integer_precision(all_parsers):
|
| 209 |
+
# Gh 7072
|
| 210 |
+
s = """1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765
|
| 211 |
+
5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389"""
|
| 212 |
+
parser = all_parsers
|
| 213 |
+
result = parser.read_csv(StringIO(s), header=None)[4]
|
| 214 |
+
expected = Series([4321583677327450765, 4321113141090630389], name=4)
|
| 215 |
+
tm.assert_series_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_iterator.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
from io import StringIO
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from pandas import (
|
| 10 |
+
DataFrame,
|
| 11 |
+
concat,
|
| 12 |
+
)
|
| 13 |
+
import pandas._testing as tm
|
| 14 |
+
|
| 15 |
+
pytestmark = pytest.mark.usefixtures("pyarrow_skip")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_iterator(all_parsers):
|
| 19 |
+
# see gh-6607
|
| 20 |
+
data = """index,A,B,C,D
|
| 21 |
+
foo,2,3,4,5
|
| 22 |
+
bar,7,8,9,10
|
| 23 |
+
baz,12,13,14,15
|
| 24 |
+
qux,12,13,14,15
|
| 25 |
+
foo2,12,13,14,15
|
| 26 |
+
bar2,12,13,14,15
|
| 27 |
+
"""
|
| 28 |
+
parser = all_parsers
|
| 29 |
+
kwargs = {"index_col": 0}
|
| 30 |
+
|
| 31 |
+
expected = parser.read_csv(StringIO(data), **kwargs)
|
| 32 |
+
with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader:
|
| 33 |
+
first_chunk = reader.read(3)
|
| 34 |
+
tm.assert_frame_equal(first_chunk, expected[:3])
|
| 35 |
+
|
| 36 |
+
last_chunk = reader.read(5)
|
| 37 |
+
tm.assert_frame_equal(last_chunk, expected[3:])
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_iterator2(all_parsers):
|
| 41 |
+
parser = all_parsers
|
| 42 |
+
data = """A,B,C
|
| 43 |
+
foo,1,2,3
|
| 44 |
+
bar,4,5,6
|
| 45 |
+
baz,7,8,9
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
with parser.read_csv(StringIO(data), iterator=True) as reader:
|
| 49 |
+
result = list(reader)
|
| 50 |
+
|
| 51 |
+
expected = DataFrame(
|
| 52 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 53 |
+
index=["foo", "bar", "baz"],
|
| 54 |
+
columns=["A", "B", "C"],
|
| 55 |
+
)
|
| 56 |
+
tm.assert_frame_equal(result[0], expected)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_iterator_stop_on_chunksize(all_parsers):
|
| 60 |
+
# gh-3967: stopping iteration when chunksize is specified
|
| 61 |
+
parser = all_parsers
|
| 62 |
+
data = """A,B,C
|
| 63 |
+
foo,1,2,3
|
| 64 |
+
bar,4,5,6
|
| 65 |
+
baz,7,8,9
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
with parser.read_csv(StringIO(data), chunksize=1) as reader:
|
| 69 |
+
result = list(reader)
|
| 70 |
+
|
| 71 |
+
assert len(result) == 3
|
| 72 |
+
expected = DataFrame(
|
| 73 |
+
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
|
| 74 |
+
index=["foo", "bar", "baz"],
|
| 75 |
+
columns=["A", "B", "C"],
|
| 76 |
+
)
|
| 77 |
+
tm.assert_frame_equal(concat(result), expected)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize(
|
| 81 |
+
"kwargs", [{"iterator": True, "chunksize": 1}, {"iterator": True}, {"chunksize": 1}]
|
| 82 |
+
)
|
| 83 |
+
def test_iterator_skipfooter_errors(all_parsers, kwargs):
|
| 84 |
+
msg = "'skipfooter' not supported for iteration"
|
| 85 |
+
parser = all_parsers
|
| 86 |
+
data = "a\n1\n2"
|
| 87 |
+
|
| 88 |
+
with pytest.raises(ValueError, match=msg):
|
| 89 |
+
with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _:
|
| 90 |
+
pass
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_iteration_open_handle(all_parsers):
|
| 94 |
+
parser = all_parsers
|
| 95 |
+
kwargs = {"header": None}
|
| 96 |
+
|
| 97 |
+
with tm.ensure_clean() as path:
|
| 98 |
+
with open(path, "w") as f:
|
| 99 |
+
f.write("AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG")
|
| 100 |
+
|
| 101 |
+
with open(path) as f:
|
| 102 |
+
for line in f:
|
| 103 |
+
if "CCC" in line:
|
| 104 |
+
break
|
| 105 |
+
|
| 106 |
+
result = parser.read_csv(f, **kwargs)
|
| 107 |
+
expected = DataFrame({0: ["DDD", "EEE", "FFF", "GGG"]})
|
| 108 |
+
tm.assert_frame_equal(result, expected)
|
videochat2/lib/python3.10/site-packages/pandas/tests/io/parser/common/test_read_errors.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tests that work on both the Python and C engines but do not have a
|
| 3 |
+
specific classification into the other test modules.
|
| 4 |
+
"""
|
| 5 |
+
import codecs
|
| 6 |
+
import csv
|
| 7 |
+
from io import StringIO
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from pandas.compat import PY311
|
| 16 |
+
from pandas.errors import (
|
| 17 |
+
EmptyDataError,
|
| 18 |
+
ParserError,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
from pandas import DataFrame
|
| 22 |
+
import pandas._testing as tm
|
| 23 |
+
|
| 24 |
+
pytestmark = pytest.mark.usefixtures("pyarrow_skip")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_empty_decimal_marker(all_parsers):
|
| 28 |
+
data = """A|B|C
|
| 29 |
+
1|2,334|5
|
| 30 |
+
10|13|10.
|
| 31 |
+
"""
|
| 32 |
+
# Parsers support only length-1 decimals
|
| 33 |
+
msg = "Only length-1 decimal markers supported"
|
| 34 |
+
parser = all_parsers
|
| 35 |
+
|
| 36 |
+
with pytest.raises(ValueError, match=msg):
|
| 37 |
+
parser.read_csv(StringIO(data), decimal="")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_bad_stream_exception(all_parsers, csv_dir_path):
|
| 41 |
+
# see gh-13652
|
| 42 |
+
#
|
| 43 |
+
# This test validates that both the Python engine and C engine will
|
| 44 |
+
# raise UnicodeDecodeError instead of C engine raising ParserError
|
| 45 |
+
# and swallowing the exception that caused read to fail.
|
| 46 |
+
path = os.path.join(csv_dir_path, "sauron.SHIFT_JIS.csv")
|
| 47 |
+
codec = codecs.lookup("utf-8")
|
| 48 |
+
utf8 = codecs.lookup("utf-8")
|
| 49 |
+
parser = all_parsers
|
| 50 |
+
msg = "'utf-8' codec can't decode byte"
|
| 51 |
+
|
| 52 |
+
# Stream must be binary UTF8.
|
| 53 |
+
with open(path, "rb") as handle, codecs.StreamRecoder(
|
| 54 |
+
handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter
|
| 55 |
+
) as stream:
|
| 56 |
+
with pytest.raises(UnicodeDecodeError, match=msg):
|
| 57 |
+
parser.read_csv(stream)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_malformed(all_parsers):
|
| 61 |
+
# see gh-6607
|
| 62 |
+
parser = all_parsers
|
| 63 |
+
data = """ignore
|
| 64 |
+
A,B,C
|
| 65 |
+
1,2,3 # comment
|
| 66 |
+
1,2,3,4,5
|
| 67 |
+
2,3,4
|
| 68 |
+
"""
|
| 69 |
+
msg = "Expected 3 fields in line 4, saw 5"
|
| 70 |
+
with pytest.raises(ParserError, match=msg):
|
| 71 |
+
parser.read_csv(StringIO(data), header=1, comment="#")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@pytest.mark.parametrize("nrows", [5, 3, None])
|
| 75 |
+
def test_malformed_chunks(all_parsers, nrows):
|
| 76 |
+
data = """ignore
|
| 77 |
+
A,B,C
|
| 78 |
+
skip
|
| 79 |
+
1,2,3
|
| 80 |
+
3,5,10 # comment
|
| 81 |
+
1,2,3,4,5
|
| 82 |
+
2,3,4
|
| 83 |
+
"""
|
| 84 |
+
parser = all_parsers
|
| 85 |
+
msg = "Expected 3 fields in line 6, saw 5"
|
| 86 |
+
with parser.read_csv(
|
| 87 |
+
StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2]
|
| 88 |
+
) as reader:
|
| 89 |
+
with pytest.raises(ParserError, match=msg):
|
| 90 |
+
reader.read(nrows)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_catch_too_many_names(all_parsers):
|
| 94 |
+
# see gh-5156
|
| 95 |
+
data = """\
|
| 96 |
+
1,2,3
|
| 97 |
+
4,,6
|
| 98 |
+
7,8,9
|
| 99 |
+
10,11,12\n"""
|
| 100 |
+
parser = all_parsers
|
| 101 |
+
msg = (
|
| 102 |
+
"Too many columns specified: expected 4 and found 3"
|
| 103 |
+
if parser.engine == "c"
|
| 104 |
+
else "Number of passed names did not match "
|
| 105 |
+
"number of header fields in the file"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
with pytest.raises(ValueError, match=msg):
|
| 109 |
+
parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"])
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5])
|
| 113 |
+
def test_raise_on_no_columns(all_parsers, nrows):
|
| 114 |
+
parser = all_parsers
|
| 115 |
+
data = "\n" * nrows
|
| 116 |
+
|
| 117 |
+
msg = "No columns to parse from file"
|
| 118 |
+
with pytest.raises(EmptyDataError, match=msg):
|
| 119 |
+
parser.read_csv(StringIO(data))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_unexpected_keyword_parameter_exception(all_parsers):
|
| 123 |
+
# GH-34976
|
| 124 |
+
parser = all_parsers
|
| 125 |
+
|
| 126 |
+
msg = "{}\\(\\) got an unexpected keyword argument 'foo'"
|
| 127 |
+
with pytest.raises(TypeError, match=msg.format("read_csv")):
|
| 128 |
+
parser.read_csv("foo.csv", foo=1)
|
| 129 |
+
with pytest.raises(TypeError, match=msg.format("read_table")):
|
| 130 |
+
parser.read_table("foo.tsv", foo=1)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_suppress_error_output(all_parsers, capsys):
|
| 134 |
+
# see gh-15925
|
| 135 |
+
parser = all_parsers
|
| 136 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 137 |
+
expected = DataFrame({"a": [1, 4]})
|
| 138 |
+
|
| 139 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="skip")
|
| 140 |
+
tm.assert_frame_equal(result, expected)
|
| 141 |
+
|
| 142 |
+
captured = capsys.readouterr()
|
| 143 |
+
assert captured.err == ""
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_error_bad_lines(all_parsers):
|
| 147 |
+
# see gh-15925
|
| 148 |
+
parser = all_parsers
|
| 149 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 150 |
+
|
| 151 |
+
msg = "Expected 1 fields in line 3, saw 3"
|
| 152 |
+
with pytest.raises(ParserError, match=msg):
|
| 153 |
+
parser.read_csv(StringIO(data), on_bad_lines="error")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_warn_bad_lines(all_parsers, capsys):
|
| 157 |
+
# see gh-15925
|
| 158 |
+
parser = all_parsers
|
| 159 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 160 |
+
expected = DataFrame({"a": [1, 4]})
|
| 161 |
+
|
| 162 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="warn")
|
| 163 |
+
tm.assert_frame_equal(result, expected)
|
| 164 |
+
|
| 165 |
+
captured = capsys.readouterr()
|
| 166 |
+
assert "Skipping line 3" in captured.err
|
| 167 |
+
assert "Skipping line 5" in captured.err
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_read_csv_wrong_num_columns(all_parsers):
|
| 171 |
+
# Too few columns.
|
| 172 |
+
data = """A,B,C,D,E,F
|
| 173 |
+
1,2,3,4,5,6
|
| 174 |
+
6,7,8,9,10,11,12
|
| 175 |
+
11,12,13,14,15,16
|
| 176 |
+
"""
|
| 177 |
+
parser = all_parsers
|
| 178 |
+
msg = "Expected 6 fields in line 3, saw 7"
|
| 179 |
+
|
| 180 |
+
with pytest.raises(ParserError, match=msg):
|
| 181 |
+
parser.read_csv(StringIO(data))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_null_byte_char(request, all_parsers):
|
| 185 |
+
# see gh-2741
|
| 186 |
+
data = "\x00,foo"
|
| 187 |
+
names = ["a", "b"]
|
| 188 |
+
parser = all_parsers
|
| 189 |
+
|
| 190 |
+
if parser.engine == "c" or (parser.engine == "python" and PY311):
|
| 191 |
+
if parser.engine == "python" and PY311:
|
| 192 |
+
request.node.add_marker(
|
| 193 |
+
pytest.mark.xfail(
|
| 194 |
+
reason="In Python 3.11, this is read as an empty character not null"
|
| 195 |
+
)
|
| 196 |
+
)
|
| 197 |
+
expected = DataFrame([[np.nan, "foo"]], columns=names)
|
| 198 |
+
out = parser.read_csv(StringIO(data), names=names)
|
| 199 |
+
tm.assert_frame_equal(out, expected)
|
| 200 |
+
else:
|
| 201 |
+
msg = "NULL byte detected"
|
| 202 |
+
with pytest.raises(ParserError, match=msg):
|
| 203 |
+
parser.read_csv(StringIO(data), names=names)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_open_file(request, all_parsers):
|
| 207 |
+
# GH 39024
|
| 208 |
+
parser = all_parsers
|
| 209 |
+
if parser.engine == "c":
|
| 210 |
+
request.node.add_marker(
|
| 211 |
+
pytest.mark.xfail(
|
| 212 |
+
reason=f"{parser.engine} engine does not support sep=None "
|
| 213 |
+
f"with delim_whitespace=False"
|
| 214 |
+
)
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
with tm.ensure_clean() as path:
|
| 218 |
+
file = Path(path)
|
| 219 |
+
file.write_bytes(b"\xe4\na\n1")
|
| 220 |
+
|
| 221 |
+
with warnings.catch_warnings(record=True) as record:
|
| 222 |
+
# should not trigger a ResourceWarning
|
| 223 |
+
warnings.simplefilter("always", category=ResourceWarning)
|
| 224 |
+
with pytest.raises(csv.Error, match="Could not determine delimiter"):
|
| 225 |
+
parser.read_csv(file, sep=None, encoding_errors="replace")
|
| 226 |
+
assert len(record) == 0, record[0].message
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def test_invalid_on_bad_line(all_parsers):
|
| 230 |
+
parser = all_parsers
|
| 231 |
+
data = "a\n1\n1,2,3\n4\n5,6,7"
|
| 232 |
+
with pytest.raises(ValueError, match="Argument abc is invalid for on_bad_lines"):
|
| 233 |
+
parser.read_csv(StringIO(data), on_bad_lines="abc")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_bad_header_uniform_error(all_parsers):
|
| 237 |
+
parser = all_parsers
|
| 238 |
+
data = "+++123456789...\ncol1,col2,col3,col4\n1,2,3,4\n"
|
| 239 |
+
msg = "Expected 2 fields in line 2, saw 4"
|
| 240 |
+
if parser.engine == "c":
|
| 241 |
+
msg = (
|
| 242 |
+
"Could not construct index. Requested to use 1 "
|
| 243 |
+
"number of columns, but 3 left to parse."
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
with pytest.raises(ParserError, match=msg):
|
| 247 |
+
parser.read_csv(StringIO(data), index_col=0, on_bad_lines="error")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_on_bad_lines_warn_correct_formatting(all_parsers, capsys):
|
| 251 |
+
# see gh-15925
|
| 252 |
+
parser = all_parsers
|
| 253 |
+
data = """1,2
|
| 254 |
+
a,b
|
| 255 |
+
a,b,c
|
| 256 |
+
a,b,d
|
| 257 |
+
a,b
|
| 258 |
+
"""
|
| 259 |
+
expected = DataFrame({"1": "a", "2": ["b"] * 2})
|
| 260 |
+
|
| 261 |
+
result = parser.read_csv(StringIO(data), on_bad_lines="warn")
|
| 262 |
+
tm.assert_frame_equal(result, expected)
|
| 263 |
+
|
| 264 |
+
captured = capsys.readouterr()
|
| 265 |
+
if parser.engine == "c":
|
| 266 |
+
warn = """Skipping line 3: expected 2 fields, saw 3
|
| 267 |
+
Skipping line 4: expected 2 fields, saw 3
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
else:
|
| 271 |
+
warn = """Skipping line 3: Expected 2 fields in line 3, saw 3
|
| 272 |
+
Skipping line 4: Expected 2 fields in line 4, saw 3
|
| 273 |
+
"""
|
| 274 |
+
assert captured.err == warn
|