Skip to content

Commit dd8cba2

Browse files
gfyoungjreback
authored andcommitted
BUG: Patch read_csv NA values behaviour
Patches the following behaviour when `na_values` is passed in as a dictionary: 1. Prevent aliasing in case `na_values` was defined in a broader scope. 2. Respect column indices as keys when doing NA conversions. Closes pandas-dev#14203. Author: gfyoung <[email protected]> Closes pandas-dev#14751 from gfyoung/csv-na-values-patching and squashes the following commits: cac422c [gfyoung] BUG: Respect column indices for dict-like na_values 1439c27 [gfyoung] BUG: Prevent aliasing of dict na_values
1 parent 6f4e36a commit dd8cba2

File tree

4 files changed

+62
-14
lines changed

4 files changed

+62
-14
lines changed

doc/source/whatsnew/v0.19.2.txt

+2
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ Bug Fixes
4040

4141
- Compat with ``dateutil==2.6.0``; segfault reported in the testing suite (:issue:`14621`)
4242
- Allow ``nanoseconds`` in ``Timestamp.replace`` as a kwarg (:issue:`14621`)
43+
- Bug in ``pd.read_csv`` in which aliasing was being done for ``na_values`` when passed in as a dictionary (:issue:`14203`)
44+
- Bug in ``pd.read_csv`` in which column indices for a dict-like ``na_values`` were not being respected (:issue:`14203`)
4345
- Bug in ``pd.read_csv`` where reading files fails, if the number of headers is equal to the number of lines in the file (:issue:`14515`)
4446
- Bug in ``pd.read_csv`` for the Python engine in which an unhelpful error message was being raised when multi-char delimiters were not being respected with quotes (:issue:`14582`)
4547
- Fix bugs (:issue:`14734`, :issue:`13654`) in ``pd.read_sas`` and ``pandas.io.sas.sas7bdat.SAS7BDATReader`` that caused problems when reading a SAS file incrementally.

pandas/io/parsers.py

+22-3
Original file line numberDiff line numberDiff line change
@@ -2055,9 +2055,27 @@ def _clean_mapping(mapping):
20552055
else:
20562056
clean_dtypes = _clean_mapping(self.dtype)
20572057

2058-
return self._convert_to_ndarrays(data, self.na_values, self.na_fvalues,
2059-
self.verbose, clean_conv,
2060-
clean_dtypes)
2058+
# Apply NA values.
2059+
clean_na_values = {}
2060+
clean_na_fvalues = {}
2061+
2062+
if isinstance(self.na_values, dict):
2063+
for col in self.na_values:
2064+
na_value = self.na_values[col]
2065+
na_fvalue = self.na_fvalues[col]
2066+
2067+
if isinstance(col, int) and col not in self.orig_names:
2068+
col = self.orig_names[col]
2069+
2070+
clean_na_values[col] = na_value
2071+
clean_na_fvalues[col] = na_fvalue
2072+
else:
2073+
clean_na_values = self.na_values
2074+
clean_na_fvalues = self.na_fvalues
2075+
2076+
return self._convert_to_ndarrays(data, clean_na_values,
2077+
clean_na_fvalues, self.verbose,
2078+
clean_conv, clean_dtypes)
20612079

20622080
def _to_recarray(self, data, columns):
20632081
dtypes = []
@@ -2767,6 +2785,7 @@ def _clean_na_values(na_values, keep_default_na=True):
27672785
na_values = []
27682786
na_fvalues = set()
27692787
elif isinstance(na_values, dict):
2788+
na_values = na_values.copy() # Prevent aliasing.
27702789
if keep_default_na:
27712790
for k, v in compat.iteritems(na_values):
27722791
if not is_list_like(v):

pandas/io/tests/parser/na_values.py

+23
Original file line numberDiff line numberDiff line change
@@ -266,3 +266,26 @@ def test_na_values_scalar(self):
266266
out = self.read_csv(StringIO(data), names=names,
267267
na_values={'a': 2, 'b': 1})
268268
tm.assert_frame_equal(out, expected)
269+
270+
def test_na_values_dict_aliasing(self):
271+
na_values = {'a': 2, 'b': 1}
272+
na_values_copy = na_values.copy()
273+
274+
names = ['a', 'b']
275+
data = '1,2\n2,1'
276+
277+
expected = DataFrame([[1.0, 2.0], [np.nan, np.nan]], columns=names)
278+
out = self.read_csv(StringIO(data), names=names, na_values=na_values)
279+
280+
tm.assert_frame_equal(out, expected)
281+
tm.assert_dict_equal(na_values, na_values_copy)
282+
283+
def test_na_values_dict_col_index(self):
284+
# see gh-14203
285+
286+
data = 'a\nfoo\n1'
287+
na_values = {0: 'foo'}
288+
289+
out = self.read_csv(StringIO(data), na_values=na_values)
290+
expected = DataFrame({'a': [np.nan, 1]})
291+
tm.assert_frame_equal(out, expected)

pandas/parser.pyx

+15-11
Original file line numberDiff line numberDiff line change
@@ -1262,19 +1262,23 @@ cdef class TextReader:
12621262
return None, set()
12631263

12641264
if isinstance(self.na_values, dict):
1265+
key = None
12651266
values = None
1267+
12661268
if name is not None and name in self.na_values:
1267-
values = self.na_values[name]
1268-
if values is not None and not isinstance(values, list):
1269-
values = list(values)
1270-
fvalues = self.na_fvalues[name]
1271-
if fvalues is not None and not isinstance(fvalues, set):
1272-
fvalues = set(fvalues)
1273-
else:
1274-
if i in self.na_values:
1275-
return self.na_values[i], self.na_fvalues[i]
1276-
else:
1277-
return _NA_VALUES, set()
1269+
key = name
1270+
elif i in self.na_values:
1271+
key = i
1272+
else: # No na_values provided for this column.
1273+
return _NA_VALUES, set()
1274+
1275+
values = self.na_values[key]
1276+
if values is not None and not isinstance(values, list):
1277+
values = list(values)
1278+
1279+
fvalues = self.na_fvalues[key]
1280+
if fvalues is not None and not isinstance(fvalues, set):
1281+
fvalues = set(fvalues)
12781282

12791283
return _ensure_encoded(values), fvalues
12801284
else:

0 commit comments

Comments
 (0)