Debian Codegraph @

dask/dataframe/io/tests/test_csv.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import annotations
2
3 import contextlib
4 import gzip
5 import os
6 import warnings
7 from io import BytesIO, StringIO
8 from unittest import mock
9
10 import pytest
11
12 pd = pytest.importorskip("pandas")
13 dd = pytest.importorskip("dask.dataframe")
14
15 import fsspec
16 from fsspec.compression import compr
17 from packaging.version import Version
18 from tlz import partition_all, valmap
19
20 import dask
21 from dask.base import compute_as_if_collection
22 from dask.bytes.core import read_bytes
23 from dask.bytes.utils import compress
24 from dask.core import flatten
•25 import dask.dataframe as dd
26 from dask.dataframe._compat import PANDAS_GE_220, PANDAS_GE_300, tm
27 from dask.dataframe.io.csv import (
28 _infer_block_size,
29 auto_blocksize,
30 block_mask,
31 pandas_read_text,
32 text_blocks_to_pandas,
33 )
34 from dask.dataframe.optimize import optimize_dataframe_getitem
35 from dask.dataframe.utils import (
36 assert_eq,
37 get_string_dtype,
38 has_known_categories,
39 pyarrow_strings_enabled,
40 )
41 from dask.layers import DataFrameIOLayer
42 from dask.utils import filetext, filetexts, tmpdir, tmpfile
43 from dask.utils_test import hlg_layer
44
45 # List of available compression format for test_read_csv_compression
46 compression_fmts = [fmt for fmt in compr] + [None]
47
•48 DASK_EXPR_ENABLED = dd._dask_expr_enabled()
49
50 def normalize_text(s):
51 return "\n".join(map(str.strip, s.strip().split("\n")))
52
53
54 def parse_filename(path):
55 return os.path.split(path)[1]
56
57
58 csv_text = """
59 name,amount
60 Alice,100
61 Bob,-200
62 Charlie,300
63 Dennis,400
64 Edith,-500
65 Frank,600
66 Alice,200
67 Frank,-200
68 Bob,600
69 Alice,400
70 Frank,200
71 Alice,300
72 Edith,600
73 """.strip()
74
75 tsv_text = csv_text.replace(",", "\t")
76
77 tsv_text2 = """
78 name amount
79 Alice 100
80 Bob -200
81 Charlie 300
82 Dennis 400
83 Edith -500
84 Frank 600
85 Alice 200
86 Frank -200
87 Bob 600
88 Alice 400
89 Frank 200
90 Alice 300
91 Edith 600
92 """.strip()
93
94 timeseries = """
95 Date,Open,High,Low,Close,Volume,Adj Close
96 2015-08-28,198.50,199.839996,197.919998,199.240005,143298900,199.240005
97 2015-08-27,197.020004,199.419998,195.210007,199.160004,266244700,199.160004
98 2015-08-26,192.080002,194.789993,188.369995,194.679993,328058100,194.679993
99 2015-08-25,195.429993,195.449997,186.919998,187.229996,353966700,187.229996
100 2015-08-24,197.630005,197.630005,182.399994,189.550003,478672400,189.550003
101 2015-08-21,201.729996,203.940002,197.520004,197.630005,328271500,197.630005
102 2015-08-20,206.509995,208.289993,203.899994,204.009995,185865600,204.009995
103 2015-08-19,209.089996,210.009995,207.350006,208.279999,167316300,208.279999
104 2015-08-18,210.259995,210.679993,209.699997,209.929993,70043800,209.929993
105 """.strip()
106
107 csv_files = {
108 "2014-01-01.csv": b"name,amount,id\nAlice,100,1\nBob,200,2\nCharlie,300,3\n",
109 "2014-01-02.csv": b"name,amount,id\n",
110 "2014-01-03.csv": b"name,amount,id\nDennis,400,4\nEdith,500,5\nFrank,600,6\n",
111 }
112
113 tsv_files = {k: v.replace(b",", b"\t") for (k, v) in csv_files.items()}
114
115 fwf_files = {
116 "2014-01-01.csv": (
117 b" name amount id\n"
118 b" Alice 100 1\n"
119 b" Bob 200 2\n"
120 b" Charlie 300 3\n"
121 ),
122 "2014-01-02.csv": b" name amount id\n",
123 "2014-01-03.csv": (
124 b" name amount id\n"
125 b" Dennis 400 4\n"
126 b" Edith 500 5\n"
127 b" Frank 600 6\n"
128 ),
129 }
130
131
132 def read_files(file_names=csv_files):
133 df = pd.concat([pd.read_csv(BytesIO(csv_files[k])) for k in sorted(file_names)])
134 df = df.astype({"name": get_string_dtype(), "amount": int, "id": int})
135 return df
136
137
138 def read_files_with(file_names, handler, **kwargs):
139 df = pd.concat([handler(n, **kwargs) for n in sorted(file_names)])
140 df = df.astype({"name": get_string_dtype(), "amount": int, "id": int})
141 return df
142
143
144 comment_header = b"""# some header lines
145 # that may be present
146 # in a data file
147 # before any data"""
148
149 comment_footer = b"""# some footer lines
150 # that may be present
151 # at the end of the file"""
152
153 csv_units_row = b"str, int, int\n"
154 tsv_units_row = csv_units_row.replace(b",", b"\t")
155
156
157 csv_and_table = pytest.mark.parametrize(
158 "reader,files",
159 [
160 (pd.read_csv, csv_files),
161 (pd.read_table, tsv_files),
162 (pd.read_fwf, fwf_files),
163 ],
164 )
165
166
167 @csv_and_table
168 def test_pandas_read_text(reader, files):
169 b = files["2014-01-01.csv"]
170 df = pandas_read_text(reader, b, b"", {})
171 assert list(df.columns) == ["name", "amount", "id"]
172 assert len(df) == 3
173 assert df.id.sum() == 1 + 2 + 3
174
175
176 @csv_and_table
177 def test_pandas_read_text_kwargs(reader, files):
178 b = files["2014-01-01.csv"]
179 df = pandas_read_text(reader, b, b"", {"usecols": ["name", "id"]})
180 assert list(df.columns) == ["name", "id"]
181
182
183 @csv_and_table
184 def test_pandas_read_text_dtype_coercion(reader, files):
185 b = files["2014-01-01.csv"]
186 df = pandas_read_text(reader, b, b"", {}, {"amount": "float"})
187 assert df.amount.dtype == "float"
188
189
190 @csv_and_table
191 def test_pandas_read_text_with_header(reader, files):
192 b = files["2014-01-01.csv"]
193 header, b = b.split(b"\n", 1)
194 header = header + b"\n"
195 df = pandas_read_text(reader, b, header, {})
196 assert list(df.columns) == ["name", "amount", "id"]
197 assert len(df) == 3
198 assert df.id.sum() == 1 + 2 + 3
199
200
201 @pytest.mark.skipif(dd._dask_expr_enabled(), reason="not supported")
202 @csv_and_table
203 def test_text_blocks_to_pandas_simple(reader, files):
204 blocks = [[files[k]] for k in sorted(files)]
205 kwargs = {}
206 head = pandas_read_text(reader, files["2014-01-01.csv"], b"", {})
207 header = files["2014-01-01.csv"].split(b"\n")[0] + b"\n"
208
209 df = text_blocks_to_pandas(reader, blocks, header, head, kwargs)
210 assert isinstance(df, dd.DataFrame)
211 assert list(df.columns) == ["name", "amount", "id"]
212
213 values = text_blocks_to_pandas(reader, blocks, header, head, kwargs)
214 assert isinstance(values, dd.DataFrame)
215 assert hasattr(values, "dask")
216 assert len(values.dask) == 6 if pyarrow_strings_enabled() else 3
217
218 assert_eq(df.amount.sum(), 100 + 200 + 300 + 400 + 500 + 600)
219
220
221 @csv_and_table
222 def test_text_blocks_to_pandas_kwargs(reader, files):
223 blocks = [files[k] for k in sorted(files)]
224 blocks = [[b] for b in blocks]
225 kwargs = {"usecols": ["name", "id"]}
226 head = pandas_read_text(reader, files["2014-01-01.csv"], b"", kwargs)
227 header = files["2014-01-01.csv"].split(b"\n")[0] + b"\n"
228
229 df = text_blocks_to_pandas(reader, blocks, header, head, kwargs)
230 assert list(df.columns) == ["name", "id"]
231 result = df.compute()
232 assert (result.columns == df.columns).all()
233
234
235 @csv_and_table
236 def test_text_blocks_to_pandas_blocked(reader, files):
237 expected = read_files()
238 header = files["2014-01-01.csv"].split(b"\n")[0] + b"\n"
239 blocks = []
240 for k in sorted(files):
241 b = files[k]
242 lines = b.split(b"\n")
243 blocks.append([b"\n".join(bs) for bs in partition_all(2, lines)])
244
245 df = text_blocks_to_pandas(reader, blocks, header, expected.head(), {})
246 assert_eq(
247 df.compute().reset_index(drop=True),
248 expected.reset_index(drop=True),
249 check_dtype=False,
250 )
251
252 expected2 = expected[["name", "id"]]
253 df = text_blocks_to_pandas(
254 reader, blocks, header, expected2.head(), {"usecols": ["name", "id"]}
255 )
256 assert_eq(
257 df.compute().reset_index(drop=True),
258 expected2.reset_index(drop=True),
259 check_dtype=False,
260 )
261
262
263 @pytest.mark.parametrize(
264 "dd_read,pd_read,files",
265 [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)],
266 )
267 def test_skiprows(dd_read, pd_read, files):
268 files = {name: comment_header + b"\n" + content for name, content in files.items()}
269 skip = len(comment_header.splitlines())
270 with filetexts(files, mode="b"):
271 df = dd_read("2014-01-*.csv", skiprows=skip)
272 expected_df = read_files_with(files, pd_read, skiprows=skip)
273 assert_eq(df, expected_df, check_dtype=False)
274
275
276 @pytest.mark.parametrize(
277 "dd_read,pd_read,files",
278 [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)],
279 )
280 def test_comment(dd_read, pd_read, files):
281 files = {
282 name: comment_header
283 + b"\n"
284 + content.replace(b"\n", b"# just some comment\n", 1)
285 for name, content in files.items()
286 }
287 with filetexts(files, mode="b"):
288 df = dd_read("2014-01-*.csv", comment="#")
289 expected_df = read_files_with(files, pd_read, comment="#")
290 assert_eq(df, expected_df, check_dtype=False)
291
292
293 @pytest.mark.parametrize(
294 "dd_read,pd_read,files",
295 [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)],
296 )
297 def test_skipfooter(dd_read, pd_read, files):
298 files = {name: content + b"\n" + comment_footer for name, content in files.items()}
299 skip = len(comment_footer.splitlines())
300 with filetexts(files, mode="b"):
301 df = dd_read("2014-01-*.csv", skipfooter=skip, engine="python")
302 expected_df = read_files_with(files, pd_read, skipfooter=skip, engine="python")
303 assert_eq(df, expected_df, check_dtype=False)
304
305
306 @pytest.mark.parametrize(
307 "dd_read,pd_read,files,units",
308 [
309 (dd.read_csv, pd.read_csv, csv_files, csv_units_row),
310 (dd.read_table, pd.read_table, tsv_files, tsv_units_row),
311 ],
312 )
313 def test_skiprows_as_list(dd_read, pd_read, files, units):
314 files = {
315 name: (comment_header + b"\n" + content.replace(b"\n", b"\n" + units, 1))
316 for name, content in files.items()
317 }
318 skip = [0, 1, 2, 3, 5]
319 with filetexts(files, mode="b"):
320 df = dd_read("2014-01-*.csv", skiprows=skip)
321 expected_df = read_files_with(files, pd_read, skiprows=skip)
322 assert_eq(df, expected_df, check_dtype=False)
323
324
325 csv_blocks = [
326 [b"aa,bb\n1,1.0\n2,2.0", b"10,20\n30,40"],
327 [b"aa,bb\n1,1.0\n2,2.0", b"10,20\n30,40"],
328 ]
329
330 tsv_blocks = [
331 [b"aa\tbb\n1\t1.0\n2\t2.0", b"10\t20\n30\t40"],
332 [b"aa\tbb\n1\t1.0\n2\t2.0", b"10\t20\n30\t40"],
333 ]
334
335
336 @pytest.mark.parametrize(
337 "reader,blocks", [(pd.read_csv, csv_blocks), (pd.read_table, tsv_blocks)]
338 )
339 def test_enforce_dtypes(reader, blocks):
340 head = reader(BytesIO(blocks[0][0]), header=0)
341 header = blocks[0][0].split(b"\n")[0] + b"\n"
342 dfs = text_blocks_to_pandas(reader, blocks, header, head, {})
343 dfs = dask.compute(dfs, scheduler="sync")
344 assert all(df.dtypes.to_dict() == head.dtypes.to_dict() for df in dfs)
345
346
•347 @pytest.mark.skipif("not DASK_EXPR_ENABLED")
348 @pytest.mark.parametrize(
349 "reader,blocks", [(pd.read_csv, csv_blocks), (pd.read_table, tsv_blocks)]
350 )
351 def test_enforce_columns(reader, blocks):
352 # Replace second header with different column name
353 blocks = [blocks[0], [blocks[1][0].replace(b"a", b"A"), blocks[1][1]]]
354 head = reader(BytesIO(blocks[0][0]), header=0)
355 header = blocks[0][0].split(b"\n")[0] + b"\n"
356 with pytest.raises(ValueError):
357 dfs = text_blocks_to_pandas(reader, blocks, header, head, {}, enforce=True)
358 dask.compute(*dfs, scheduler="sync")
359
360
361 #############################
362 # read_csv and read_table #
363 #############################
364
365
366 @pytest.mark.parametrize(
367 "dd_read,pd_read,text,sep",
368 [
369 (dd.read_csv, pd.read_csv, csv_text, ","),
370 (dd.read_table, pd.read_table, tsv_text, "\t"),
371 (dd.read_table, pd.read_table, tsv_text2, r"\s+"),
372 ],
373 )
374 def test_read_csv(dd_read, pd_read, text, sep):
375 with filetext(text) as fn:
376 f = dd_read(fn, blocksize=30, lineterminator=os.linesep, sep=sep)
377 assert list(f.columns) == ["name", "amount"]
378 # index may be different
379 result = f.compute(scheduler="sync").reset_index(drop=True)
380 assert_eq(result, pd_read(fn, sep=sep))
381
382
383 def test_read_csv_convert_string_config():
384 pytest.importorskip("pyarrow", reason="Requires pyarrow strings")
385 with filetext(csv_text) as fn:
386 df = pd.read_csv(fn)
387 with dask.config.set({"dataframe.convert-string": True}):
388 ddf = dd.read_csv(fn)
389 df_pyarrow = df.astype({"name": "string[pyarrow]"})
390 assert_eq(df_pyarrow, ddf, check_index=False)
391
392
393 @pytest.mark.parametrize(
394 "dd_read,pd_read,text,skip",
395 [
396 (dd.read_csv, pd.read_csv, csv_text, 7),
397 (dd.read_table, pd.read_table, tsv_text, [1, 13]),
398 ],
399 )
400 def test_read_csv_large_skiprows(dd_read, pd_read, text, skip):
401 names = ["name", "amount"]
402 with filetext(text) as fn:
403 actual = dd_read(fn, skiprows=skip, names=names)
404 assert_eq(actual, pd_read(fn, skiprows=skip, names=names))
405
406
407 @pytest.mark.parametrize(
408 "dd_read,pd_read,text,skip",
409 [
410 (dd.read_csv, pd.read_csv, csv_text, 7),
411 (dd.read_table, pd.read_table, tsv_text, [1, 12]),
412 ],
413 )
414 def test_read_csv_skiprows_only_in_first_partition(dd_read, pd_read, text, skip):
415 names = ["name", "amount"]
416 with filetext(text) as fn:
417 with pytest.warns(UserWarning, match="sample=blocksize"):
418 actual = dd_read(fn, blocksize=200, skiprows=skip, names=names).compute()
419 assert_eq(actual, pd_read(fn, skiprows=skip, names=names))
420
421 with pytest.warns(UserWarning):
422 # if new sample does not contain all the skiprows, raise error
423 with pytest.raises(ValueError):
424 dd_read(fn, blocksize=30, skiprows=skip, names=names)
425
426
427 @pytest.mark.parametrize(
428 "dd_read,pd_read,files",
429 [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)],
430 )
431 def test_read_csv_files(dd_read, pd_read, files):
432 expected = read_files()
433 with filetexts(files, mode="b"):
434 df = dd_read("2014-01-*.csv")
435 assert_eq(df, expected, check_dtype=False)
436
437 fn = "2014-01-01.csv"
438 df = dd_read(fn)
439 expected2 = pd_read(BytesIO(files[fn]))
440 assert_eq(df, expected2, check_dtype=False)
441
442
443 @pytest.mark.parametrize(
444 "dd_read,pd_read,files",
445 [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)],
446 )
447 def test_read_csv_files_list(dd_read, pd_read, files):
448 with filetexts(files, mode="b"):
449 subset = sorted(files)[:2] # Just first 2
450 sol = read_files(subset)
451 res = dd_read(subset)
452 assert_eq(res, sol, check_dtype=False)
453
454 with pytest.raises(ValueError):
455 dd_read([])
456
457
458 @pytest.mark.parametrize(
459 "dd_read,files", [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]
460 )
461 def test_read_csv_include_path_column(dd_read, files):
462 with filetexts(files, mode="b"):
463 df = dd_read(
464 "2014-01-*.csv",
465 include_path_column=True,
466 converters={"path": parse_filename},
467 )
468 filenames = df.path.compute().unique()
469 assert "2014-01-01.csv" in filenames
470 assert "2014-01-02.csv" not in filenames
471 assert "2014-01-03.csv" in filenames
472
473
474 @pytest.mark.parametrize(
475 "dd_read,files", [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]
476 )
477 def test_read_csv_include_path_column_as_str(dd_read, files):
478 with filetexts(files, mode="b"):
479 df = dd_read(
480 "2014-01-*.csv",
481 include_path_column="filename",
482 converters={"filename": parse_filename},
483 )
484 filenames = df.filename.compute().unique()
485 assert "2014-01-01.csv" in filenames
486 assert "2014-01-02.csv" not in filenames
487 assert "2014-01-03.csv" in filenames
488
489
490 @pytest.mark.parametrize(
491 "dd_read,files", [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]
492 )
493 def test_read_csv_include_path_column_with_duplicate_name(dd_read, files):
494 with filetexts(files, mode="b"):
495 with pytest.raises(ValueError):
496 dd_read("2014-01-*.csv", include_path_column="name")
497
498
499 @pytest.mark.parametrize(
500 "dd_read,files", [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]
501 )
502 def test_read_csv_include_path_column_is_dtype_category(dd_read, files):
503 with filetexts(files, mode="b"):
504 df = dd_read("2014-01-*.csv", include_path_column=True)
505 assert df.path.dtype == "category"
506 assert has_known_categories(df.path)
507
508 dfs = dd_read("2014-01-*.csv", include_path_column=True)
509 result = dfs.compute()
510 assert result.path.dtype == "category"
511 assert has_known_categories(result.path)
512
513
514 @pytest.mark.parametrize(
515 "dd_read,files", [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]
516 )
517 def test_read_csv_include_path_column_with_multiple_partitions_per_file(dd_read, files):
518 with filetexts(files, mode="b"):
519 df = dd_read("2014-01-*.csv", blocksize="10B", include_path_column=True)
520 assert df.npartitions > 3
521 assert df.path.dtype == "category"
522 assert has_known_categories(df.path)
523
524 dfs = dd_read("2014-01-*.csv", blocksize="10B", include_path_column=True)
525 result = dfs.compute()
526 assert result.path.dtype == "category"
527 assert has_known_categories(result.path)
528
529
530 # After this point, we test just using read_csv, as all functionality
531 # for both is implemented using the same code.
532
533
534 def test_read_csv_index():
535 with filetext(csv_text) as fn:
536 f = dd.read_csv(fn, blocksize=20).set_index("amount")
537 result = f.compute(scheduler="sync")
538 assert result.index.name == "amount"
539
540 blocks = compute_as_if_collection(
541 dd.DataFrame, f.dask, f.__dask_keys__(), scheduler="sync"
542 )
543 for i, block in enumerate(blocks):
544 if i < len(f.divisions) - 2:
545 assert (block.index < f.divisions[i + 1]).all()
546 if i > 0:
547 assert (block.index >= f.divisions[i]).all()
548
549 expected = pd.read_csv(fn).set_index("amount")
550 assert_eq(result, expected)
551
552
553 def test_read_csv_skiprows_range():
554 with filetext(csv_text) as fn:
555 f = dd.read_csv(fn, skiprows=range(5))
556 result = f
557 expected = pd.read_csv(fn, skiprows=range(5))
558 assert_eq(result, expected)
559
560
561 def test_usecols():
562 with filetext(timeseries) as fn:
563 df = dd.read_csv(fn, blocksize=30, usecols=["High", "Low"])
564 df_select = df[["High"]]
565 expected = pd.read_csv(fn, usecols=["High", "Low"])
566 expected_select = expected[["High"]]
567 assert (df.compute().values == expected.values).all()
568 assert (df_select.compute().values == expected_select.values).all()
569
570
571 def test_string_blocksize():
572 with filetext(timeseries) as fn:
573 a = dd.read_csv(fn, blocksize="30B")
574 b = dd.read_csv(fn, blocksize="30")
575 assert a.npartitions == b.npartitions
576
577 c = dd.read_csv(fn, blocksize="64MiB")
578 assert c.npartitions == 1
579
580
581 def test_skipinitialspace():
582 text = normalize_text(
583 """
584 name, amount
585 Alice,100
586 Bob,-200
587 Charlie,300
588 Dennis,400
589 Edith,-500
590 Frank,600
591 """
592 )
593
594 with filetext(text) as fn:
595 df = dd.read_csv(fn, skipinitialspace=True, blocksize=20)
596
597 assert "amount" in df.columns
598 assert df.amount.max().compute() == 600
599
600
601 def test_consistent_dtypes():
602 text = normalize_text(
603 """
604 name,amount
605 Alice,100.5
606 Bob,-200.5
607 Charlie,300
608 Dennis,400
609 Edith,-500
610 Frank,600
611 """
612 )
613
614 with filetext(text) as fn:
615 df = dd.read_csv(fn, blocksize=30)
616 assert df.amount.compute().dtype == float
617
618
619 def test_consistent_dtypes_2():
620 text1 = normalize_text(
621 """
622 name,amount
623 Alice,100
624 Bob,-200
625 Charlie,300
626 """
627 )
628
629 text2 = normalize_text(
630 """
631 name,amount
632 1,400
633 2,-500
634 Frank,600
635 """
636 )
637 string_dtype = get_string_dtype()
638 with filetexts({"foo.1.csv": text1, "foo.2.csv": text2}):
639 df = dd.read_csv("foo.*.csv", blocksize=25)
640 assert df.name.dtype == string_dtype
641 assert df.name.compute().dtype == string_dtype
642
643
644 def test_categorical_dtypes():
645 text1 = normalize_text(
646 """
647 fruit,count
648 apple,10
649 apple,25
650 pear,100
651 orange,15
652 """
653 )
654
655 text2 = normalize_text(
656 """
657 fruit,count
658 apple,200
659 banana,300
660 orange,400
661 banana,10
662 """
663 )
664
665 with filetexts({"foo.1.csv": text1, "foo.2.csv": text2}):
666 df = dd.read_csv("foo.*.csv", dtype={"fruit": "category"}, blocksize=25)
667 assert df.fruit.dtype == "category"
668 assert not has_known_categories(df.fruit)
669 res = df.compute()
670 assert res.fruit.dtype == "category"
671 assert sorted(res.fruit.cat.categories) == ["apple", "banana", "orange", "pear"]
672
673
674 def test_categorical_known():
675 text1 = normalize_text(
676 """
677 A,B
678 a,a
679 b,b
680 a,a
681 """
682 )
683 text2 = normalize_text(
684 """
685 A,B
686 a,a
687 b,b
688 c,c
689 """
690 )
691 dtype = pd.api.types.CategoricalDtype(["a", "b", "c"], ordered=False)
692 with filetexts({"foo.1.csv": text1, "foo.2.csv": text2}):
693 result = dd.read_csv("foo.*.csv", dtype={"A": "category", "B": "category"})
694 assert result.A.cat.known is False
695 assert result.B.cat.known is False
696 expected = pd.DataFrame(
697 {
698 "A": pd.Categorical(
699 ["a", "b", "a", "a", "b", "c"], categories=dtype.categories
700 ),
701 "B": pd.Categorical(
702 ["a", "b", "a", "a", "b", "c"], categories=dtype.categories
703 ),
704 },
705 index=[0, 1, 2, 0, 1, 2],
706 )
707 assert_eq(result, expected)
708
709 # Specify a dtype
710 result = dd.read_csv("foo.*.csv", dtype={"A": dtype, "B": "category"})
711 assert result.A.cat.known is True
712 assert result.B.cat.known is False
713 tm.assert_index_equal(result.A.cat.categories, dtype.categories)
714 assert result.A.cat.ordered is False
715 assert_eq(result, expected)
716
717 # ordered
718 dtype = pd.api.types.CategoricalDtype(["a", "b", "c"], ordered=True)
719 result = dd.read_csv("foo.*.csv", dtype={"A": dtype, "B": "category"})
720 expected["A"] = expected["A"].cat.as_ordered()
721 assert result.A.cat.known is True
722 assert result.B.cat.known is False
723 assert result.A.cat.ordered is True
724
725 assert_eq(result, expected)
726
727 # Specify "unknown" categories
728 result = dd.read_csv(
729 "foo.*.csv", dtype=pd.api.types.CategoricalDtype(ordered=False)
730 )
731 assert result.A.cat.known is False
732
733 result = dd.read_csv("foo.*.csv", dtype="category")
734 assert result.A.cat.known is False
735
736
737 @pytest.mark.slow
738 @pytest.mark.parametrize("compression", ["infer", "gzip"])
739 def test_compression_multiple_files(compression):
740 with tmpdir() as tdir:
741 f = gzip.open(os.path.join(tdir, "a.csv.gz"), "wb")
742 f.write(csv_text.encode())
743 f.close()
744
745 f = gzip.open(os.path.join(tdir, "b.csv.gz"), "wb")
746 f.write(csv_text.encode())
747 f.close()
748
749 with pytest.warns(UserWarning):
750 df = dd.read_csv(os.path.join(tdir, "*.csv.gz"), compression=compression)
751
752 assert len(df.compute()) == (len(csv_text.split("\n")) - 1) * 2
753
754
755 def test_empty_csv_file():
756 with filetext("a,b") as fn:
757 df = dd.read_csv(fn, header=0)
758 assert len(df.compute()) == 0
759 assert list(df.columns) == ["a", "b"]
760
761
762 def test_read_csv_no_sample():
763 with filetexts(csv_files, mode="b") as fn:
764 df = dd.read_csv(fn, sample=False)
765 assert list(df.columns) == ["name", "amount", "id"]
766
767
768 def test_read_csv_sensitive_to_enforce():
769 with filetexts(csv_files, mode="b"):
770 a = dd.read_csv("2014-01-*.csv", enforce=True)
771 b = dd.read_csv("2014-01-*.csv", enforce=False)
772 assert a._name != b._name
773
774
775 @pytest.mark.parametrize("blocksize", [None, 10])
776 @pytest.mark.parametrize("fmt", compression_fmts)
777 def test_read_csv_compression(fmt, blocksize):
778 if fmt and fmt not in compress:
779 pytest.skip("compress function not provided for %s" % fmt)
780
781 expected = read_files()
782 suffix = {"gzip": ".gz", "bz2": ".bz2", "zip": ".zip", "xz": ".xz"}.get(fmt, "")
783 files2 = valmap(compress[fmt], csv_files) if fmt else csv_files
784 renamed_files = {k + suffix: v for k, v in files2.items()}
785 with filetexts(renamed_files, mode="b"):
786 # This test is using `compression="infer"` (the default) for
787 # read_csv. The paths must have the appropriate extension.
788 if fmt and blocksize:
789 with pytest.warns(UserWarning):
790 df = dd.read_csv("2014-01-*.csv" + suffix, blocksize=blocksize)
791 else:
792 df = dd.read_csv("2014-01-*.csv" + suffix, blocksize=blocksize)
793 assert_eq(
794 df.compute(scheduler="sync").reset_index(drop=True),
795 expected.reset_index(drop=True),
796 check_dtype=False,
797 )
798
799
800 @pytest.mark.skip
801 def test_warn_non_seekable_files():
802 files2 = valmap(compress["gzip"], csv_files)
803 with filetexts(files2, mode="b"):
804 with pytest.warns(UserWarning) as w:
805 df = dd.read_csv("2014-01-*.csv", compression="gzip")
806 assert df.npartitions == 3
807
808 assert len(w) == 1
809 msg = str(w[0].message)
810 assert "gzip" in msg
811 assert "blocksize=None" in msg
812
813 with warnings.catch_warnings(record=True) as record:
814 df = dd.read_csv("2014-01-*.csv", compression="gzip", blocksize=None)
815 assert not record
816
817 with pytest.raises(NotImplementedError):
818 with pytest.warns(UserWarning): # needed for pytest
819 df = dd.read_csv("2014-01-*.csv", compression="foo")
820
821
822 def test_windows_line_terminator():
823 text = "a,b\r\n1,2\r\n2,3\r\n3,4\r\n4,5\r\n5,6\r\n6,7"
824 with filetext(text) as fn:
825 df = dd.read_csv(fn, blocksize=5, lineterminator="\r\n")
826 assert df.b.sum().compute() == 2 + 3 + 4 + 5 + 6 + 7
827 assert df.a.sum().compute() == 1 + 2 + 3 + 4 + 5 + 6
828
829
830 @pytest.mark.parametrize("header", [1, 2, 3])
831 def test_header_int(header):
832 text = (
833 "id0,name0,x0,y0\n"
834 "id,name,x,y\n"
835 "1034,Victor,-0.25,0.84\n"
836 "998,Xavier,-0.48,-0.13\n"
837 "999,Zelda,0.00,0.47\n"
838 "980,Alice,0.67,-0.98\n"
839 "989,Zelda,-0.04,0.03\n"
840 )
841 with filetexts({"test_header_int.csv": text}):
842 df = dd.read_csv("test_header_int.csv", header=header, blocksize=64)
843 expected = pd.read_csv("test_header_int.csv", header=header)
844 assert_eq(df, expected, check_index=False)
845
846
847 def test_header_None():
848 with filetexts({".tmp.1.csv": "1,2", ".tmp.2.csv": "", ".tmp.3.csv": "3,4"}):
849 df = dd.read_csv(".tmp.*.csv", header=None)
850 expected = pd.DataFrame({0: [1, 3], 1: [2, 4]})
851 assert_eq(df.compute().reset_index(drop=True), expected)
852
853
854 def test_auto_blocksize():
855 assert isinstance(auto_blocksize(3000, 15), int)
856 assert auto_blocksize(3000, 3) == 100
857 assert auto_blocksize(5000, 2) == 250
858
859
860 def test__infer_block_size(monkeypatch):
861 """
862 psutil returns a total memory of `None` on some systems
863 see https://github.com/dask/dask/pull/7601
864 """
865 psutil = pytest.importorskip("psutil")
866
867 class MockOutput:
868 total = None
869
870 def mock_virtual_memory():
871 return MockOutput
872
873 monkeypatch.setattr(psutil, "virtual_memory", mock_virtual_memory)
874 assert _infer_block_size()
875
876
877 def test_auto_blocksize_max64mb():
878 blocksize = auto_blocksize(1000000000000, 3)
879 assert blocksize == int(64e6)
880 assert isinstance(blocksize, int)
881
882
883 def test_auto_blocksize_csv(monkeypatch):
884 psutil = pytest.importorskip("psutil")
885 total_memory = psutil.virtual_memory().total
886 cpu_count = psutil.cpu_count()
887 mock_read_bytes = mock.Mock(wraps=read_bytes)
888 monkeypatch.setattr(dask.dataframe.io.csv, "read_bytes", mock_read_bytes)
889
890 expected_block_size = auto_blocksize(total_memory, cpu_count)
891 with filetexts(csv_files, mode="b"):
892 dd.read_csv("2014-01-01.csv")
893 assert mock_read_bytes.called
894 assert mock_read_bytes.call_args[1]["blocksize"] == expected_block_size
895
896
897 def test_head_partial_line_fix():
898 files = {
899 ".overflow1.csv": (
900 "a,b\n0,'abcdefghijklmnopqrstuvwxyz'\n1,'abcdefghijklmnopqrstuvwxyz'"
901 ),
902 ".overflow2.csv": "a,b\n111111,-11111\n222222,-22222\n333333,-33333\n",
903 }
904 with filetexts(files):
905 # 64 byte file, 52 characters is mid-quote; this should not cause exception in head-handling code.
906 dd.read_csv(".overflow1.csv", sample=52)
907
908 # 35 characters is cuts off before the second number on the last line
909 # Should sample to end of line, otherwise pandas will infer `b` to be
910 # a float dtype
911 df = dd.read_csv(".overflow2.csv", sample=35)
912 assert (df.dtypes == "i8").all()
913
914
915 def test_read_csv_raises_on_no_files():
916 fn = ".not.a.real.file.csv"
917 try:
918 dd.read_csv(fn)
919 assert False
920 except OSError as e:
921 assert fn in str(e)
922
923
924 def test_read_csv_has_deterministic_name():
925 with filetext(csv_text) as fn:
926 a = dd.read_csv(fn)
927 b = dd.read_csv(fn)
928 assert a._name == b._name
929 assert sorted(a.dask.keys(), key=str) == sorted(b.dask.keys(), key=str)
930 assert isinstance(a._name, str)
931
932 c = dd.read_csv(fn, skiprows=1, na_values=[0])
933 assert a._name != c._name
934
935
936 def test_multiple_read_csv_has_deterministic_name():
937 with filetexts({"_foo.1.csv": csv_text, "_foo.2.csv": csv_text}):
938 a = dd.read_csv("_foo.*.csv")
939 b = dd.read_csv("_foo.*.csv")
940
941 assert sorted(a.dask.keys(), key=str) == sorted(b.dask.keys(), key=str)
942
943
944 def test_read_csv_has_different_names_based_on_blocksize():
945 with filetext(csv_text) as fn:
946 a = dd.read_csv(fn, blocksize="10kB")
947 b = dd.read_csv(fn, blocksize="20kB")
948 assert a._name != b._name
949
950
951 def test_csv_with_integer_names():
952 with filetext("alice,1\nbob,2") as fn:
953 df = dd.read_csv(fn, header=None)
954 assert list(df.columns) == [0, 1]
955
956
957 def test_late_dtypes():
958 text = "numbers,names,more_numbers,integers,dates\n"
959 for _ in range(1000):
960 text += "1,,2,3,2017-10-31 00:00:00\n"
961 text += "1.5,bar,2.5,3,4998-01-01 00:00:00\n"
962
963 date_msg = (
964 "\n"
965 "\n"
966 "-------------------------------------------------------------\n"
967 "\n"
968 "The following columns also failed to properly parse as dates:\n"
969 "\n"
970 "- dates\n"
971 "\n"
972 "This is usually due to an invalid value in that column. To\n"
973 "diagnose and fix it's recommended to drop these columns from the\n"
974 "`parse_dates` keyword, and manually convert them to dates later\n"
975 "using `dd.to_datetime`."
976 )
977
978 with filetext(text) as fn:
979 if PANDAS_GE_300:
980 sol = pd.read_csv(fn, parse_dates=["dates"])
981 else:
982 sol = pd.read_csv(fn)
983 msg = (
984 "Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n"
985 "\n"
986 "+--------------+---------+----------+\n"
987 "| Column | Found | Expected |\n"
988 "+--------------+---------+----------+\n"
989 "| more_numbers | float64 | int64 |\n"
990 "| names | object | float64 |\n"
991 "| numbers | float64 | int64 |\n"
992 "+--------------+---------+----------+\n"
993 "\n"
994 "- names\n"
995 " ValueError(.*)\n"
996 "\n"
997 "Usually this is due to dask's dtype inference failing, and\n"
998 "*may* be fixed by specifying dtypes manually by adding:\n"
999 "\n"
1000 "dtype={'more_numbers': 'float64',\n"
1001 " 'names': 'object',\n"
1002 " 'numbers': 'float64'}\n"
1003 "\n"
1004 "to the call to `read_csv`/`read_table`."
1005 )
1006
1007 with pytest.raises(ValueError) as e:
1008 dd.read_csv(fn, sample=50, parse_dates=["dates"]).compute(scheduler="sync")
1009 assert e.match(msg + date_msg)
1010
1011 with pytest.raises(ValueError) as e:
1012 dd.read_csv(fn, sample=50).compute(scheduler="sync")
1013 assert e.match(msg)
1014
1015 msg = (
1016 "Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n"
1017 "\n"
1018 "+--------------+---------+----------+\n"
1019 "| Column | Found | Expected |\n"
1020 "+--------------+---------+----------+\n"
1021 "| more_numbers | float64 | int64 |\n"
1022 "| numbers | float64 | int64 |\n"
1023 "+--------------+---------+----------+\n"
1024 "\n"
1025 "Usually this is due to dask's dtype inference failing, and\n"
1026 "*may* be fixed by specifying dtypes manually by adding:\n"
1027 "\n"
1028 "dtype={'more_numbers': 'float64',\n"
1029 " 'numbers': 'float64'}\n"
1030 "\n"
1031 "to the call to `read_csv`/`read_table`.\n"
1032 "\n"
1033 "Alternatively, provide `assume_missing=True` to interpret\n"
1034 "all unspecified integer columns as floats."
1035 )
1036
1037 with pytest.raises(ValueError) as e:
1038 dd.read_csv(fn, sample=50, dtype={"names": "O"}).compute(scheduler="sync")
1039 assert str(e.value) == msg
1040
1041 if PANDAS_GE_300:
1042 # Specifying dtypes works
1043 res = dd.read_csv(
1044 fn,
1045 sample=50,
1046 dtype={"more_numbers": float, "names": object, "numbers": float},
1047 parse_dates=["dates"],
1048 )
1049 assert_eq(res, sol)
1050 return
1051
1052 with pytest.raises(ValueError) as e:
1053 dd.read_csv(
1054 fn, sample=50, parse_dates=["dates"], dtype={"names": "O"}
1055 ).compute(scheduler="sync")
1056 assert str(e.value) == msg + date_msg
1057
1058 msg = (
1059 "Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n"
1060 "\n"
1061 "The following columns failed to properly parse as dates:\n"
1062 "\n"
1063 "- dates\n"
1064 "\n"
1065 "This is usually due to an invalid value in that column. To\n"
1066 "diagnose and fix it's recommended to drop these columns from the\n"
1067 "`parse_dates` keyword, and manually convert them to dates later\n"
1068 "using `dd.to_datetime`."
1069 )
1070
1071 with pytest.raises(ValueError) as e:
1072 dd.read_csv(
1073 fn,
1074 sample=50,
1075 parse_dates=["dates"],
1076 dtype={"more_numbers": float, "names": object, "numbers": float},
1077 ).compute(scheduler="sync")
1078 assert str(e.value) == msg
1079
1080 # Specifying dtypes works
1081 res = dd.read_csv(
1082 fn,
1083 sample=50,
1084 dtype={"more_numbers": float, "names": object, "numbers": float},
1085 )
1086 assert_eq(res, sol)
1087
1088
1089 def test_assume_missing():
1090 text = "numbers,names,more_numbers,integers\n"
1091 for _ in range(1000):
1092 text += "1,foo,2,3\n"
1093 text += "1.5,bar,2.5,3\n"
1094 with filetext(text) as fn:
1095 sol = pd.read_csv(fn)
1096
1097 # assume_missing affects all columns
1098 res = dd.read_csv(fn, sample=50, assume_missing=True)
1099 assert_eq(res, sol.astype({"integers": float}))
1100
1101 # assume_missing doesn't override specified dtypes
1102 res = dd.read_csv(
1103 fn, sample=50, assume_missing=True, dtype={"integers": "int64"}
1104 )
1105 assert_eq(res, sol)
1106
1107 # assume_missing works with dtype=None
1108 res = dd.read_csv(fn, sample=50, assume_missing=True, dtype=None)
1109 assert_eq(res, sol.astype({"integers": float}))
1110
1111 text = "numbers,integers\n"
1112 for _ in range(1000):
1113 text += "1,2\n"
1114 text += "1.5,2\n"
1115
1116 with filetext(text) as fn:
1117 sol = pd.read_csv(fn)
1118
1119 # assume_missing ignored when all dtypes specified
1120 df = dd.read_csv(fn, sample=30, dtype="int64", assume_missing=True)
1121 assert df.numbers.dtype == "int64"
1122
1123
1124 def test_index_col():
1125 with filetext(csv_text) as fn:
1126 try:
1127 dd.read_csv(fn, blocksize=30, index_col="name")
1128 assert False
1129 except ValueError as e:
1130 assert "set_index" in str(e)
1131
1132 df = pd.read_csv(fn, index_col=False)
1133 ddf = dd.read_csv(fn, blocksize=30, index_col=False)
1134 assert_eq(df, ddf, check_index=False)
1135
1136
1137 def test_read_csv_with_datetime_index_partitions_one():
1138 with filetext(timeseries) as fn:
1139 df = pd.read_csv(
1140 fn, index_col=0, header=0, usecols=[0, 4], parse_dates=["Date"]
1141 )
1142 # blocksize set to explicitly set to single chunk
1143 ddf = dd.read_csv(
1144 fn, header=0, usecols=[0, 4], parse_dates=["Date"], blocksize=10000000
1145 ).set_index("Date")
1146 assert_eq(df, ddf)
1147
1148 # because fn is so small, by default, this will only be one chunk
1149 ddf = dd.read_csv(fn, header=0, usecols=[0, 4], parse_dates=["Date"]).set_index(
1150 "Date"
1151 )
1152 assert_eq(df, ddf)
1153
1154
1155 def test_read_csv_with_datetime_index_partitions_n():
1156 with filetext(timeseries) as fn:
1157 df = pd.read_csv(
1158 fn, index_col=0, header=0, usecols=[0, 4], parse_dates=["Date"]
1159 )
1160 # because fn is so small, by default, set chunksize small
1161 ddf = dd.read_csv(
1162 fn, header=0, usecols=[0, 4], parse_dates=["Date"], blocksize=400
1163 ).set_index("Date")
1164 assert_eq(df, ddf)
1165
1166
1167 # utf-8-sig and utf-16 both start with a BOM.
1168 @pytest.mark.parametrize("encoding", ["utf-8-sig", "utf-16", "utf-16-le", "utf-16-be"])
1169 def test_encoding_gh601(encoding):
1170 ar = pd.Series(range(0, 100))
1171 br = ar % 7
1172 cr = br * 3.3
1173 dr = br / 1.9836
1174 test_df = pd.DataFrame({"a": ar, "b": br, "c": cr, "d": dr})
1175
1176 with tmpfile(".csv") as fn:
1177 test_df.to_csv(fn, encoding=encoding, index=False)
1178
1179 a = pd.read_csv(fn, encoding=encoding)
1180 d = dd.read_csv(fn, encoding=encoding, blocksize=1000)
1181 d = d.compute()
1182 d.index = range(len(d.index))
1183 assert_eq(d, a)
1184
1185
1186 def test_read_csv_header_issue_823():
1187 text = """a b c-d\n1 2 3\n4 5 6""".replace(" ", "\t")
1188 with filetext(text) as fn:
1189 df = dd.read_csv(fn, sep="\t")
1190 assert_eq(df, pd.read_csv(fn, sep="\t"))
1191
1192 df = dd.read_csv(fn, delimiter="\t")
1193 assert_eq(df, pd.read_csv(fn, delimiter="\t"))
1194
1195
1196 def test_none_usecols():
1197 with filetext(csv_text) as fn:
1198 df = dd.read_csv(fn, usecols=None)
1199 assert_eq(df, pd.read_csv(fn, usecols=None))
1200
1201
1202 def test_parse_dates_multi_column():
1203 pdmc_text = normalize_text(
1204 """
1205 ID,date,time
1206 10,2003-11-04,180036
1207 11,2003-11-05,125640
1208 12,2003-11-01,2519
1209 13,2003-10-22,142559
1210 14,2003-10-24,163113
1211 15,2003-10-20,170133
1212 16,2003-11-11,160448
1213 17,2003-11-03,171759
1214 18,2003-11-07,190928
1215 19,2003-10-21,84623
1216 20,2003-10-25,192207
1217 21,2003-11-13,180156
1218 22,2003-11-15,131037
1219 """
1220 )
1221
1222 ctx = contextlib.nullcontext()
1223 if PANDAS_GE_300:
1224 # Removed in pandas=3.0
1225 ctx = pytest.raises(TypeError, match="list indices")
1226 elif PANDAS_GE_220:
1227 # Deprecated in pandas=2.2.0
1228 ctx = pytest.warns(FutureWarning, match="nested")
1229
1230 with ctx:
1231 with filetext(pdmc_text) as fn:
1232 ddf = dd.read_csv(fn, parse_dates=[["date", "time"]])
1233 df = pd.read_csv(fn, parse_dates=[["date", "time"]])
1234
1235 assert (df.columns == ddf.columns).all()
1236 assert len(df) == len(ddf)
1237
1238
1239 def test_read_csv_sep():
1240 sep_text = normalize_text(
1241 """
1242 name###amount
1243 alice###100
1244 bob###200
1245 charlie###300"""
1246 )
1247
1248 with filetext(sep_text) as fn:
1249 ddf = dd.read_csv(fn, sep="###", engine="python")
1250 df = pd.read_csv(fn, sep="###", engine="python")
1251
1252 assert (df.columns == ddf.columns).all()
1253 assert len(df) == len(ddf)
1254
1255
1256 def test_read_csv_slash_r():
1257 data = b"0,my\n1,data\n" * 1000 + b"2,foo\rbar"
1258 with filetext(data, mode="wb") as fn:
1259 dd.read_csv(
1260 fn,
1261 header=None,
1262 sep=",",
1263 lineterminator="\n",
1264 names=["a", "b"],
1265 blocksize=200,
1266 ).compute(scheduler="sync")
1267
1268
1269 def test_read_csv_singleton_dtype():
1270 data = b"a,b\n1,2\n3,4\n5,6"
1271 with filetext(data, mode="wb") as fn:
1272 assert_eq(pd.read_csv(fn, dtype=float), dd.read_csv(fn, dtype=float))
1273
1274
1275 def test_read_csv_arrow_engine():
1276 pytest.importorskip("pyarrow")
1277 sep_text = normalize_text(
1278 """
1279 a,b
1280 1,2
1281 """
1282 )
1283
1284 with filetext(sep_text) as fn:
1285 assert_eq(pd.read_csv(fn, engine="pyarrow"), dd.read_csv(fn, engine="pyarrow"))
1286
1287
1288 def test_robust_column_mismatch():
1289 files = csv_files.copy()
1290 k = sorted(files)[-1]
1291 files[k] = files[k].replace(b"name", b"Name")
1292 with filetexts(files, mode="b"):
1293 ddf = dd.read_csv(
1294 "2014-01-*.csv", header=None, skiprows=1, names=["name", "amount", "id"]
1295 )
1296 df = pd.read_csv("2014-01-01.csv")
1297 assert (df.columns == ddf.columns).all()
1298 assert_eq(ddf, ddf)
1299
1300
1301 def test_different_columns_are_allowed():
1302 files = csv_files.copy()
1303 k = sorted(files)[-1]
1304 files[k] = files[k].replace(b"name", b"address")
1305 with filetexts(files, mode="b"):
1306 ddf = dd.read_csv("2014-01-*.csv")
1307
1308 # since enforce is False, meta doesn't have to match computed
1309 assert (ddf.columns == ["name", "amount", "id"]).all()
1310 assert (ddf.compute().columns == ["name", "amount", "id", "address"]).all()
1311
1312
1313 def test_error_if_sample_is_too_small():
1314 text = "AAAAA,BBBBB,CCCCC,DDDDD,EEEEE\n1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15"
1315 with filetext(text) as fn:
1316 # Sample size stops mid header row
1317 sample = 20
1318 with pytest.raises(ValueError):
1319 dd.read_csv(fn, sample=sample)
1320
1321 # Saying no header means this is fine
1322 assert_eq(
1323 dd.read_csv(fn, sample=sample, header=None), pd.read_csv(fn, header=None)
1324 )
1325
1326 skiptext = "# skip\n# these\n# lines\n"
1327
1328 text = skiptext + text
1329 with filetext(text) as fn:
1330 # Sample size stops mid header row
1331 sample = 20 + len(skiptext)
1332 with pytest.raises(ValueError):
1333 dd.read_csv(fn, sample=sample, skiprows=3)
1334
1335 # Saying no header means this is fine
1336 assert_eq(
1337 dd.read_csv(fn, sample=sample, header=None, skiprows=3),
1338 pd.read_csv(fn, header=None, skiprows=3),
1339 )
1340
1341
1342 def test_read_csv_names_not_none():
1343 text = (
1344 "Alice,100\n"
1345 "Bob,-200\n"
1346 "Charlie,300\n"
1347 "Dennis,400\n"
1348 "Edith,-500\n"
1349 "Frank,600\n"
1350 )
1351 names = ["name", "amount"]
1352 with filetext(text) as fn:
1353 ddf = dd.read_csv(fn, names=names, blocksize=16)
1354 df = pd.read_csv(fn, names=names)
1355 assert_eq(df, ddf, check_index=False)
1356
1357
1358 ############
1359 # to_csv #
1360 ############
1361
1362
1363 def test_to_csv():
1364 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1365
1366 for npartitions in [1, 2]:
1367 a = dd.from_pandas(df, npartitions)
1368 with tmpdir() as dn:
1369 a.to_csv(dn, index=False)
1370 result = dd.read_csv(os.path.join(dn, "*")).compute().reset_index(drop=True)
1371 assert_eq(result, df)
1372
1373 with tmpdir() as dn:
1374 r = a.to_csv(dn, index=False, compute=False)
1375 paths = dask.compute(*r, scheduler="sync")
1376 # this is a tuple rather than a list since it's the output of dask.compute
1377 assert paths == tuple(
1378 os.path.join(dn, f"{n}.part") for n in range(npartitions)
1379 )
1380 result = dd.read_csv(os.path.join(dn, "*")).compute().reset_index(drop=True)
1381 assert_eq(result, df)
1382
1383 with tmpdir() as dn:
1384 fn = os.path.join(dn, "data_*.csv")
1385 paths = a.to_csv(fn, index=False)
1386 assert paths == [
1387 os.path.join(dn, f"data_{n}.csv") for n in range(npartitions)
1388 ]
1389 result = dd.read_csv(fn).compute().reset_index(drop=True)
1390 assert_eq(result, df)
1391
1392
1393 def test_to_csv_multiple_files_cornercases():
1394 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1395 a = dd.from_pandas(df, 2)
1396 with tmpdir() as dn:
1397 with pytest.raises(ValueError):
1398 fn = os.path.join(dn, "data_*_*.csv")
1399 a.to_csv(fn)
1400
1401 df16 = pd.DataFrame(
1402 {
1403 "x": [
1404 "a",
1405 "b",
1406 "c",
1407 "d",
1408 "e",
1409 "f",
1410 "g",
1411 "h",
1412 "i",
1413 "j",
1414 "k",
1415 "l",
1416 "m",
1417 "n",
1418 "o",
1419 "p",
1420 ],
1421 "y": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
1422 }
1423 )
1424 a = dd.from_pandas(df16, 16)
1425 with tmpdir() as dn:
1426 fn = os.path.join(dn, "data_*.csv")
1427 a.to_csv(fn, index=False)
1428 result = dd.read_csv(fn).compute().reset_index(drop=True)
1429 assert_eq(result, df16)
1430
1431 # test handling existing files when links are optimized out
1432 a = dd.from_pandas(df, 2)
1433 with tmpdir() as dn:
1434 a.to_csv(dn, index=False)
1435 fn = os.path.join(dn, "data_*.csv")
1436 a.to_csv(fn, mode="w", index=False)
1437 result = dd.read_csv(fn).compute().reset_index(drop=True)
1438 assert_eq(result, df)
1439
1440 # test handling existing files when links are optimized out
1441 a = dd.from_pandas(df16, 16)
1442 with tmpdir() as dn:
1443 a.to_csv(dn, index=False)
1444 fn = os.path.join(dn, "data_*.csv")
1445 a.to_csv(fn, mode="w", index=False)
1446 result = dd.read_csv(fn).compute().reset_index(drop=True)
1447 assert_eq(result, df16)
1448
1449
1450 def test_to_single_csv():
1451 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1452
1453 for npartitions in [1, 2]:
1454 a = dd.from_pandas(df, npartitions)
1455 with tmpdir() as dn:
1456 fn = os.path.join(dn, "test.csv")
1457 a.to_csv(fn, index=False, single_file=True)
1458 result = dd.read_csv(fn).compute().reset_index(drop=True)
1459 assert_eq(result, df)
1460
1461 with tmpdir() as dn:
1462 fn = os.path.join(dn, "test.csv")
1463 r = a.to_csv(fn, index=False, compute=False, single_file=True)
1464 dask.compute(r, scheduler="sync")
1465 result = dd.read_csv(fn).compute().reset_index(drop=True)
1466 assert_eq(result, df)
1467
1468
1469 def test_to_single_csv_with_name_function():
1470 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1471 a = dd.from_pandas(df, 1)
1472 with tmpdir() as dn:
1473 fn = os.path.join(dn, "test.csv")
1474 with pytest.raises(
1475 ValueError,
1476 match="name_function is not supported under the single file mode",
1477 ):
1478 a.to_csv(fn, name_function=lambda x: x, index=False, single_file=True)
1479
1480
1481 def test_to_single_csv_with_header_first_partition_only():
1482 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1483 a = dd.from_pandas(df, 1)
1484 with tmpdir() as dn:
1485 fn = os.path.join(dn, "test.csv")
1486 with pytest.raises(
1487 ValueError,
1488 match="header_first_partition_only cannot be False in the single file mode.",
1489 ):
1490 a.to_csv(
1491 fn, index=False, header_first_partition_only=False, single_file=True
1492 )
1493
1494
1495 def test_to_csv_with_single_file_and_exclusive_mode():
1496 df0 = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1497 df = dd.from_pandas(df0, npartitions=2)
1498 with tmpdir() as directory:
1499 csv_path = os.path.join(directory, "test.csv")
1500 df.to_csv(csv_path, index=False, mode="x", single_file=True)
1501 result = dd.read_csv(os.path.join(directory, "*")).compute()
1502 assert_eq(result, df0, check_index=False)
1503
1504
1505 def test_to_csv_single_file_exlusive_mode_no_overwrite():
1506 df0 = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1507 df = dd.from_pandas(df0, npartitions=2)
1508 with tmpdir() as directory:
1509 csv_path = os.path.join(str(directory), "test.csv")
1510 df.to_csv(csv_path, index=False, mode="x", single_file=True)
1511 assert os.path.exists(csv_path)
1512 # mode="x" should fail if file already exists
1513 with pytest.raises(FileExistsError):
1514 df.to_csv(csv_path, index=False, mode="x", single_file=True)
1515 # but mode="w" will overwrite an existing file
1516 df.to_csv(csv_path, index=False, mode="w", single_file=True)
1517
1518
1519 def test_to_single_csv_gzip():
1520 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1521
1522 for npartitions in [1, 2]:
1523 a = dd.from_pandas(df, npartitions)
1524 with tmpdir() as dn:
1525 fn = os.path.join(dn, "test.csv.gz")
1526 a.to_csv(fn, index=False, compression="gzip", single_file=True)
1527 result = pd.read_csv(fn, compression="gzip").reset_index(drop=True)
1528 assert_eq(result, df)
1529
1530
1531 @pytest.mark.xfail(reason="to_csv does not support compression")
1532 def test_to_csv_gzip():
1533 df = pd.DataFrame(
1534 {"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]}, index=[1.0, 2.0, 3.0, 4.0]
1535 )
1536
1537 for npartitions in [1, 2]:
1538 a = dd.from_pandas(df, npartitions)
1539 with tmpfile("csv") as fn:
1540 a.to_csv(fn, compression="gzip")
1541 result = pd.read_csv(fn, index_col=0, compression="gzip")
1542 tm.assert_frame_equal(result, df)
1543
1544
1545 @pytest.mark.skipif(
1546 Version(fsspec.__version__) == Version("2023.9.1"),
1547 reason="https://github.com/dask/dask/issues/10515",
1548 )
1549 def test_to_csv_nodir():
1550 # See #6062 https://github.com/intake/filesystem_spec/pull/271 and
1551 df0 = pd.DataFrame(
1552 {"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]}, index=[1.0, 2.0, 3.0, 4.0]
1553 )
1554 df = dd.from_pandas(df0, npartitions=2)
1555 with tmpdir() as dir:
1556 dir0 = os.path.join(str(dir), "createme")
1557 df.to_csv(dir0)
1558 assert "createme" in os.listdir(dir)
1559 assert os.listdir(dir0)
1560 result = dd.read_csv(os.path.join(dir0, "*")).compute()
1561 assert (result.x.values == df0.x.values).all()
1562
1563
1564 def test_to_csv_simple():
1565 df0 = pd.DataFrame(
1566 {"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]}, index=[1.0, 2.0, 3.0, 4.0]
1567 )
1568 df = dd.from_pandas(df0, npartitions=2)
1569 with tmpdir() as dir:
1570 dir = str(dir)
1571 df.to_csv(dir)
1572 assert os.listdir(dir)
1573 result = dd.read_csv(os.path.join(dir, "*")).compute()
1574 assert (result.x.values == df0.x.values).all()
1575
1576
1577 def test_to_csv_with_single_file_and_append_mode():
1578 # regression test for https://github.com/dask/dask/issues/10414
1579 df0 = pd.DataFrame(
1580 {"x": ["a", "b"], "y": [1, 2]},
1581 )
1582 df1 = pd.DataFrame(
1583 {"x": ["c", "d"], "y": [3, 4]},
1584 )
1585 df = dd.from_pandas(df1, npartitions=2)
1586 with tmpdir() as dir:
1587 csv_path = os.path.join(dir, "test.csv")
1588 df0.to_csv(
1589 csv_path,
1590 index=False,
1591 )
1592 df.to_csv(
1593 csv_path,
1594 mode="a",
1595 header=False,
1596 index=False,
1597 single_file=True,
1598 )
1599 result = dd.read_csv(os.path.join(dir, "*")).compute()
1600 expected = pd.concat([df0, df1])
1601 assert assert_eq(result, expected, check_index=False)
1602
1603
1604 def test_to_csv_series():
1605 df0 = pd.Series(["a", "b", "c", "d"], index=[1.0, 2.0, 3.0, 4.0])
1606 df = dd.from_pandas(df0, npartitions=2)
1607 with tmpdir() as dir:
1608 dir = str(dir)
1609 df.to_csv(dir, header=False)
1610 assert os.listdir(dir)
1611 result = dd.read_csv(os.path.join(dir, "*"), header=None, names=["x"]).compute()
1612 assert (result.x == df0).all()
1613
1614
1615 def test_to_csv_with_get():
1616 from dask.multiprocessing import get as mp_get
1617
1618 flag = [False]
1619
1620 def my_get(*args, **kwargs):
1621 flag[0] = True
1622 return mp_get(*args, **kwargs)
1623
1624 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1625 ddf = dd.from_pandas(df, npartitions=2)
1626
1627 with tmpdir() as dn:
1628 ddf.to_csv(dn, index=False, compute_kwargs={"scheduler": my_get})
1629 assert flag[0]
1630 result = dd.read_csv(os.path.join(dn, "*"))
1631 assert_eq(result, df, check_index=False)
1632
1633
1634 def test_to_csv_warns_using_scheduler_argument():
1635 from dask.multiprocessing import get as mp_get
1636
1637 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1638 ddf = dd.from_pandas(df, npartitions=2)
1639
1640 def my_get(*args, **kwargs):
1641 return mp_get(*args, **kwargs)
1642
1643 with tmpdir() as dn:
1644 with pytest.warns(FutureWarning):
1645 ddf.to_csv(dn, index=False, scheduler=my_get)
1646
1647
1648 def test_to_csv_errors_using_multiple_scheduler_args():
1649 from dask.multiprocessing import get as mp_get
1650
1651 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1652 ddf = dd.from_pandas(df, npartitions=2)
1653
1654 def my_get(*args, **kwargs):
1655 return mp_get(*args, **kwargs)
1656
1657 with tmpdir() as dn:
1658 with pytest.raises(ValueError) and pytest.warns(FutureWarning):
1659 ddf.to_csv(
1660 dn, index=False, scheduler=my_get, compute_kwargs={"scheduler": my_get}
1661 )
1662
1663
1664 def test_to_csv_keeps_all_non_scheduler_compute_kwargs():
1665 from dask.multiprocessing import get as mp_get
1666
1667 def my_get(*args, **kwargs):
1668 assert kwargs["test_kwargs_passed"] == "foobar"
1669 return mp_get(*args, **kwargs)
1670
1671 df = pd.DataFrame({"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4]})
1672 ddf = dd.from_pandas(df, npartitions=2)
1673
1674 with tmpdir() as dn:
1675 ddf.to_csv(
1676 dn,
1677 index=False,
1678 compute_kwargs={"scheduler": my_get, "test_kwargs_passed": "foobar"},
1679 )
1680
1681
1682 def test_to_csv_paths():
1683 df = pd.DataFrame({"A": range(10)})
1684 ddf = dd.from_pandas(df, npartitions=2)
1685 paths = ddf.to_csv("foo*.csv")
1686 assert paths[0].endswith("foo0.csv")
1687 assert paths[1].endswith("foo1.csv")
1688
1689 os.remove("foo0.csv")
1690 os.remove("foo1.csv")
1691
1692
1693 @pytest.mark.parametrize("header, expected", [(False, ""), (True, "x,y\n")])
1694 def test_to_csv_header_empty_dataframe(header, expected):
1695 dfe = pd.DataFrame({"x": [], "y": []})
1696 ddfe = dd.from_pandas(dfe, npartitions=1)
1697
1698 with tmpdir() as dn:
1699 ddfe.to_csv(os.path.join(dn, "fooe*.csv"), index=False, header=header)
1700 assert not os.path.exists(os.path.join(dn, "fooe1.csv"))
1701 filename = os.path.join(dn, "fooe0.csv")
1702 with open(filename) as fp:
1703 line = fp.readline()
1704 assert line == expected
1705 os.remove(filename)
1706
1707
1708 @pytest.mark.parametrize(
1709 "header,header_first_partition_only,expected_first,expected_next",
1710 [
1711 (False, False, "a,1\n", "d,4\n"),
1712 (True, False, "x,y\n", "x,y\n"),
1713 (False, True, "a,1\n", "d,4\n"),
1714 (True, True, "x,y\n", "d,4\n"),
1715 (["aa", "bb"], False, "aa,bb\n", "aa,bb\n"),
1716 (["aa", "bb"], True, "aa,bb\n", "d,4\n"),
1717 ],
1718 )
1719 def test_to_csv_header(
1720 header, header_first_partition_only, expected_first, expected_next
1721 ):
1722 partition_count = 2
1723 df = pd.DataFrame({"x": ["a", "b", "c", "d", "e", "f"], "y": [1, 2, 3, 4, 5, 6]})
1724 ddf = dd.from_pandas(df, npartitions=partition_count)
1725
1726 with tmpdir() as dn:
1727 # Test NO header case
1728 # (header=False, header_first_chunk_only not passed)
1729 ddf.to_csv(
1730 os.path.join(dn, "fooa*.csv"),
1731 index=False,
1732 header=header,
1733 header_first_partition_only=header_first_partition_only,
1734 )
1735 filename = os.path.join(dn, "fooa0.csv")
1736 with open(filename) as fp:
1737 line = fp.readline()
1738 assert line == expected_first
1739 os.remove(filename)
1740
1741 filename = os.path.join(dn, "fooa1.csv")
1742 with open(filename) as fp:
1743 line = fp.readline()
1744 assert line == expected_next
1745 os.remove(filename)
1746
1747
1748 def test_to_csv_line_ending():
1749 df = pd.DataFrame({"x": [0]})
1750 ddf = dd.from_pandas(df, npartitions=1)
1751 expected = {b"0\r\n", b"0\n"} # either/or
1752 # For comparison...
1753 # unexpected = {b'0\r\r\n'}
1754 # This test addresses GH4809, and checks that only (at most) one
1755 # '\r' character is written per line when writing to csv.
1756 # In case it's correct (on UNIX) to have no '\r' at all, this test
1757 # considers either '\r\n' or '\n' as appropriate line endings,
1758 # but not '\r\r\n'.
1759 with tmpdir() as dn:
1760 ddf.to_csv(os.path.join(dn, "foo*.csv"), header=False, index=False)
1761 filename = os.path.join(dn, "foo0.csv")
1762 with open(filename, "rb") as f:
1763 raw = f.read()
1764 assert raw in expected
1765
1766
1767 @pytest.mark.parametrize(
1768 "block_lists",
1769 [
1770 [[1, 2], [3], [4, 5, 6]],
1771 [],
1772 [[], [], [1], [], [1]],
1773 [list(range(i)) for i in range(10)],
1774 ],
1775 )
1776 def test_block_mask(block_lists):
1777 mask = list(block_mask(block_lists))
1778 assert len(mask) == len(list(flatten(block_lists)))
1779
1780
1781 def test_reading_empty_csv_files_with_path():
1782 with tmpdir() as tdir:
1783 for k, content in enumerate(["0, 1, 2", "", "6, 7, 8"]):
1784 with open(os.path.join(tdir, str(k) + ".csv"), "w") as file:
1785 file.write(content)
1786 result = dd.read_csv(
1787 os.path.join(tdir, "*.csv"),
1788 include_path_column=True,
1789 converters={"path": parse_filename},
1790 names=["A", "B", "C"],
1791 ).compute()
1792 df = pd.DataFrame(
1793 {
1794 "A": [0, 6],
1795 "B": [1, 7],
1796 "C": [2, 8],
1797 "path": ["0.csv", "2.csv"],
1798 }
1799 )
1800 df["path"] = df["path"].astype("category")
1801 assert_eq(result, df, check_index=False)
1802
1803
1804 def test_read_csv_groupby_get_group(tmpdir):
1805 # https://github.com/dask/dask/issues/7005
1806
1807 path = os.path.join(str(tmpdir), "test.csv")
1808 df1 = pd.DataFrame([{"foo": 10, "bar": 4}])
1809 df1.to_csv(path, index=False)
1810
1811 ddf1 = dd.read_csv(path)
1812 ddfs = ddf1.groupby("foo")
1813
1814 assert_eq(df1, ddfs.get_group(10).compute())
1815
1816
1817 def test_csv_getitem_column_order(tmpdir):
1818 # See: https://github.com/dask/dask/issues/7759
1819
1820 path = os.path.join(str(tmpdir), "test.csv")
1821 columns = list("abcdefghijklmnopqrstuvwxyz")
1822 values = list(range(len(columns)))
1823
1824 df1 = pd.DataFrame([{c: v for c, v in zip(columns, values)}])
1825 df1.to_csv(path)
1826
1827 # Use disordered and duplicated column selection
1828 columns = list("hczzkylaape")
1829 df2 = dd.read_csv(path)[columns].head(1)
1830 assert_eq(df1[columns], df2)
1831
1832
1833 @pytest.mark.skip_with_pyarrow_strings # checks graph layers
1834 @pytest.mark.skipif(dd._dask_expr_enabled(), reason="layers not supported")
1835 def test_getitem_optimization_after_filter():
1836 with filetext(timeseries) as fn:
1837 expect = pd.read_csv(fn)
1838 expect = expect[expect["High"] > 205.0][["Low"]]
1839 ddf = dd.read_csv(fn)
1840 ddf = ddf[ddf["High"] > 205.0][["Low"]]
1841
1842 dsk = optimize_dataframe_getitem(ddf.dask, keys=[ddf._name])
1843 subgraph_rd = hlg_layer(dsk, "read-csv")
1844 assert isinstance(subgraph_rd, DataFrameIOLayer)
1845 assert set(subgraph_rd.columns) == {"High", "Low"}
1846 assert_eq(expect, ddf)
1847
1848
1849 def test_csv_parse_fail(tmpdir):
1850 # See GH #7680
1851 path = os.path.join(str(tmpdir), "test.csv")
1852 data = b'a,b\n1,"hi\n"\n2,"oi\n"\n'
1853 expected = pd.read_csv(BytesIO(data))
1854 with open(path, "wb") as f:
1855 f.write(data)
1856 with pytest.raises(ValueError, match="EOF encountered"):
1857 dd.read_csv(path, sample=13)
1858 df = dd.read_csv(path, sample=13, sample_rows=1)
1859 assert_eq(df, expected)
1860
1861
1862 def test_csv_name_should_be_different_even_if_head_is_same(tmpdir):
1863 # https://github.com/dask/dask/issues/7904
1864 import random
1865 from shutil import copyfile
1866
1867 old_csv_path = os.path.join(str(tmpdir), "old.csv")
1868 new_csv_path = os.path.join(str(tmpdir), "new_csv")
1869
1870 # Create random CSV
1871 with open(old_csv_path, "w") as f:
1872 for _ in range(10):
1873 f.write(
1874 f"{random.randrange(1, 10**9):09}, {random.randrange(1, 10**9):09}, {random.randrange(1, 10**9):09}\n"
1875 )
1876
1877 copyfile(old_csv_path, new_csv_path)
1878
1879 # Add three new rows
1880 with open(new_csv_path, "a") as f:
1881 for _ in range(3):
1882 f.write(
1883 f"{random.randrange(1, 10**9):09}, {random.randrange(1, 10**9):09}, {random.randrange(1, 10**9):09}\n"
1884 )
1885
1886 new_df = dd.read_csv(
1887 new_csv_path, header=None, delimiter=",", dtype=str, blocksize=None
1888 )
1889 old_df = dd.read_csv(
1890 old_csv_path, header=None, delimiter=",", dtype=str, blocksize=None
1891 )
1892
1893 assert new_df.dask.keys() != old_df.dask.keys()
1894
1895
1896 def test_select_with_include_path_column(tmpdir):
1897 # https://github.com/dask/dask/issues/9518
1898
1899 d = {"col1": [i for i in range(0, 100)], "col2": [i for i in range(100, 200)]}
1900 df = pd.DataFrame(data=d)
1901
1902 temp_path = str(tmpdir) + "/"
1903 for i in range(6):
1904 df.to_csv(f"{temp_path}file_{i}.csv", index=False)
1905
1906 ddf = dd.read_csv(temp_path + "*.csv", include_path_column=True)
1907
1908 assert_eq(ddf.col1, pd.concat([df.col1] * 6))
1909
1910
1911 @pytest.mark.parametrize("use_names", [True, False])
1912 def test_names_with_header_0(tmpdir, use_names):
1913 # This test sets `blocksize` so that we will
1914 # get two partitions in `dd.read_csv`. We are
1915 # testing that `header=0` results in the expected
1916 # behavior when `names` is also specified.
1917 # See: https://github.com/dask/dask/issues/9610
1918
1919 csv = StringIO(
1920 """\
1921 city1,1992-09-13,10
1922 city2,1992-09-13,14
1923 city3,1992-09-13,98
1924 city4,1992-09-13,13
1925 city5,1992-09-13,45
1926 city6,1992-09-13,64
1927 """
1928 )
1929
1930 if use_names:
1931 names = ["city", "date", "sales"]
1932 usecols = ["city", "sales"]
1933 else:
1934 names = usecols = None
1935
1936 path = os.path.join(str(tmpdir), "input.csv")
1937 pd.read_csv(csv, header=None).to_csv(path, index=False, header=False)
1938 df = pd.read_csv(path, header=0, names=names, usecols=usecols)
1939 ddf = dd.read_csv(
1940 path,
1941 header=0,
1942 names=names,
1943 usecols=usecols,
1944 blocksize=60,
1945 )
1946
1947 # Result should only leave out 0th row
1948 assert_eq(df, ddf, check_index=False)