test_skiprows.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests that skipped rows are properly handled during
  4. parsing for all of the parsers defined in parsers.py
  5. """
  6. from datetime import datetime
  7. import numpy as np
  8. import pytest
  9. from pandas.compat import StringIO, lrange, range
  10. from pandas.errors import EmptyDataError
  11. from pandas import DataFrame, Index
  12. import pandas.util.testing as tm
  13. @pytest.mark.parametrize("skiprows", [lrange(6), 6])
  14. def test_skip_rows_bug(all_parsers, skiprows):
  15. # see gh-505
  16. parser = all_parsers
  17. text = """#foo,a,b,c
  18. #foo,a,b,c
  19. #foo,a,b,c
  20. #foo,a,b,c
  21. #foo,a,b,c
  22. #foo,a,b,c
  23. 1/1/2000,1.,2.,3.
  24. 1/2/2000,4,5,6
  25. 1/3/2000,7,8,9
  26. """
  27. result = parser.read_csv(StringIO(text), skiprows=skiprows, header=None,
  28. index_col=0, parse_dates=True)
  29. index = Index([datetime(2000, 1, 1), datetime(2000, 1, 2),
  30. datetime(2000, 1, 3)], name=0)
  31. expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
  32. columns=[1, 2, 3], index=index)
  33. tm.assert_frame_equal(result, expected)
  34. def test_deep_skip_rows(all_parsers):
  35. # see gh-4382
  36. parser = all_parsers
  37. data = "a,b,c\n" + "\n".join([",".join([str(i), str(i + 1), str(i + 2)])
  38. for i in range(10)])
  39. condensed_data = "a,b,c\n" + "\n".join([
  40. ",".join([str(i), str(i + 1), str(i + 2)])
  41. for i in [0, 1, 2, 3, 4, 6, 8, 9]])
  42. result = parser.read_csv(StringIO(data), skiprows=[6, 8])
  43. condensed_result = parser.read_csv(StringIO(condensed_data))
  44. tm.assert_frame_equal(result, condensed_result)
  45. def test_skip_rows_blank(all_parsers):
  46. # see gh-9832
  47. parser = all_parsers
  48. text = """#foo,a,b,c
  49. #foo,a,b,c
  50. #foo,a,b,c
  51. #foo,a,b,c
  52. 1/1/2000,1.,2.,3.
  53. 1/2/2000,4,5,6
  54. 1/3/2000,7,8,9
  55. """
  56. data = parser.read_csv(StringIO(text), skiprows=6, header=None,
  57. index_col=0, parse_dates=True)
  58. index = Index([datetime(2000, 1, 1), datetime(2000, 1, 2),
  59. datetime(2000, 1, 3)], name=0)
  60. expected = DataFrame(np.arange(1., 10.).reshape((3, 3)),
  61. columns=[1, 2, 3],
  62. index=index)
  63. tm.assert_frame_equal(data, expected)
  64. @pytest.mark.parametrize("data,kwargs,expected", [
  65. ("""id,text,num_lines
  66. 1,"line 11
  67. line 12",2
  68. 2,"line 21
  69. line 22",2
  70. 3,"line 31",1""",
  71. dict(skiprows=[1]),
  72. DataFrame([[2, "line 21\nline 22", 2],
  73. [3, "line 31", 1]], columns=["id", "text", "num_lines"])),
  74. ("a,b,c\n~a\n b~,~e\n d~,~f\n f~\n1,2,~12\n 13\n 14~",
  75. dict(quotechar="~", skiprows=[2]),
  76. DataFrame([["a\n b", "e\n d", "f\n f"]], columns=["a", "b", "c"])),
  77. (("Text,url\n~example\n "
  78. "sentence\n one~,url1\n~"
  79. "example\n sentence\n two~,url2\n~"
  80. "example\n sentence\n three~,url3"),
  81. dict(quotechar="~", skiprows=[1, 3]),
  82. DataFrame([['example\n sentence\n two', 'url2']],
  83. columns=["Text", "url"]))
  84. ])
  85. def test_skip_row_with_newline(all_parsers, data, kwargs, expected):
  86. # see gh-12775 and gh-10911
  87. parser = all_parsers
  88. result = parser.read_csv(StringIO(data), **kwargs)
  89. tm.assert_frame_equal(result, expected)
  90. def test_skip_row_with_quote(all_parsers):
  91. # see gh-12775 and gh-10911
  92. parser = all_parsers
  93. data = """id,text,num_lines
  94. 1,"line '11' line 12",2
  95. 2,"line '21' line 22",2
  96. 3,"line '31' line 32",1"""
  97. exp_data = [[2, "line '21' line 22", 2],
  98. [3, "line '31' line 32", 1]]
  99. expected = DataFrame(exp_data, columns=[
  100. "id", "text", "num_lines"])
  101. result = parser.read_csv(StringIO(data), skiprows=[1])
  102. tm.assert_frame_equal(result, expected)
  103. @pytest.mark.parametrize("data,exp_data", [
  104. ("""id,text,num_lines
  105. 1,"line \n'11' line 12",2
  106. 2,"line \n'21' line 22",2
  107. 3,"line \n'31' line 32",1""",
  108. [[2, "line \n'21' line 22", 2],
  109. [3, "line \n'31' line 32", 1]]),
  110. ("""id,text,num_lines
  111. 1,"line '11\n' line 12",2
  112. 2,"line '21\n' line 22",2
  113. 3,"line '31\n' line 32",1""",
  114. [[2, "line '21\n' line 22", 2],
  115. [3, "line '31\n' line 32", 1]]),
  116. ("""id,text,num_lines
  117. 1,"line '11\n' \r\tline 12",2
  118. 2,"line '21\n' \r\tline 22",2
  119. 3,"line '31\n' \r\tline 32",1""",
  120. [[2, "line '21\n' \r\tline 22", 2],
  121. [3, "line '31\n' \r\tline 32", 1]]),
  122. ])
  123. def test_skip_row_with_newline_and_quote(all_parsers, data, exp_data):
  124. # see gh-12775 and gh-10911
  125. parser = all_parsers
  126. result = parser.read_csv(StringIO(data), skiprows=[1])
  127. expected = DataFrame(exp_data, columns=["id", "text", "num_lines"])
  128. tm.assert_frame_equal(result, expected)
  129. @pytest.mark.parametrize("line_terminator", [
  130. "\n", # "LF"
  131. "\r\n", # "CRLF"
  132. "\r" # "CR"
  133. ])
  134. def test_skiprows_lineterminator(all_parsers, line_terminator):
  135. # see gh-9079
  136. parser = all_parsers
  137. data = "\n".join(["SMOSMANIA ThetaProbe-ML2X ",
  138. "2007/01/01 01:00 0.2140 U M ",
  139. "2007/01/01 02:00 0.2141 M O ",
  140. "2007/01/01 04:00 0.2142 D M "])
  141. expected = DataFrame([["2007/01/01", "01:00", 0.2140, "U", "M"],
  142. ["2007/01/01", "02:00", 0.2141, "M", "O"],
  143. ["2007/01/01", "04:00", 0.2142, "D", "M"]],
  144. columns=["date", "time", "var", "flag",
  145. "oflag"])
  146. if parser.engine == "python" and line_terminator == "\r":
  147. pytest.skip("'CR' not respect with the Python parser yet")
  148. data = data.replace("\n", line_terminator)
  149. result = parser.read_csv(StringIO(data), skiprows=1, delim_whitespace=True,
  150. names=["date", "time", "var", "flag", "oflag"])
  151. tm.assert_frame_equal(result, expected)
  152. def test_skiprows_infield_quote(all_parsers):
  153. # see gh-14459
  154. parser = all_parsers
  155. data = "a\"\nb\"\na\n1"
  156. expected = DataFrame({"a": [1]})
  157. result = parser.read_csv(StringIO(data), skiprows=2)
  158. tm.assert_frame_equal(result, expected)
  159. @pytest.mark.parametrize("kwargs,expected", [
  160. (dict(), DataFrame({"1": [3, 5]})),
  161. (dict(header=0, names=["foo"]), DataFrame({"foo": [3, 5]}))
  162. ])
  163. def test_skip_rows_callable(all_parsers, kwargs, expected):
  164. parser = all_parsers
  165. data = "a\n1\n2\n3\n4\n5"
  166. result = parser.read_csv(StringIO(data),
  167. skiprows=lambda x: x % 2 == 0,
  168. **kwargs)
  169. tm.assert_frame_equal(result, expected)
  170. def test_skip_rows_skip_all(all_parsers):
  171. parser = all_parsers
  172. data = "a\n1\n2\n3\n4\n5"
  173. msg = "No columns to parse from file"
  174. with pytest.raises(EmptyDataError, match=msg):
  175. parser.read_csv(StringIO(data), skiprows=lambda x: True)
  176. def test_skip_rows_bad_callable(all_parsers):
  177. msg = "by zero"
  178. parser = all_parsers
  179. data = "a\n1\n2\n3\n4\n5"
  180. with pytest.raises(ZeroDivisionError, match=msg):
  181. parser.read_csv(StringIO(data), skiprows=lambda x: 1 / 0)