Skip to content

Accept range for list-requiring kwargs in pd.read_csv #17083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,8 @@ def _clean_options(self, options, engine):
if _is_index_col(index_col):
if not isinstance(index_col, (list, tuple, np.ndarray)):
index_col = [index_col]
if PY3 and isinstance(index_col, range):
index_col = list(index_col)
result['index_col'] = index_col

names = list(names) if names is not None else names
Expand Down Expand Up @@ -1191,6 +1193,11 @@ def __init__(self, kwds):

# validate header options for mi
self.header = kwds.get('header')
if PY3:
if isinstance(self.header, range):
self.header = list(self.header)
if isinstance(self.index_col, range):
self.index_col = list(self.index_col)
if isinstance(self.header, (list, tuple, np.ndarray)):
if not all(map(is_integer, self.header)):
raise ValueError("header must be integer or list of integers")
Expand All @@ -1213,7 +1220,6 @@ def __init__(self, kwds):
is_integer(self.index_col)):
raise ValueError("index_col must only contain row numbers "
"when specifying a multi-index header")

# GH 16338
elif self.header is not None and not is_integer(self.header):
raise ValueError("header must be integer or list of integers")
Expand Down
19 changes: 18 additions & 1 deletion pandas/tests/io/parser/index_col.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import pandas.util.testing as tm

from pandas import DataFrame, Index, MultiIndex
from pandas import DataFrame, Index, MultiIndex, date_range
from pandas.compat import StringIO


Expand Down Expand Up @@ -141,3 +141,20 @@ def test_empty_with_index_col_false(self):
result = self.read_csv(StringIO(data), index_col=False)
expected = DataFrame([], columns=['x', 'y'])
tm.assert_frame_equal(result, expected)

def test_range_index_col(self):
cols = MultiIndex.from_arrays([['A', 'B', 'C'], ['foo', 'bar', 'baz']])
index = date_range('2016-01-02', periods=3, freq='D')
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = DataFrame(data, index=index, columns=cols)

data = (",A,B,C\n"
",foo,bar,baz\n"
"2016-01-02,1,2,3\n"
"2016-01-03,4,5,6\n"
"2016-01-04,7,8,9"
)
res = self.read_csv(StringIO(df.to_csv()),
index_col=range(1),
header=range(2))
tm.assert_frame_equal(df, res)