@@ -272,15 +272,46 @@ def test_categorical_coerces_numeric(all_parsers):
272272 tm .assert_frame_equal (result , expected )
273273
274274
275+ def test_categorical_coerces_datetime (all_parsers ):
276+ parser = all_parsers
277+ dti = pd .DatetimeIndex (["2017-01-01" , "2018-01-01" , "2019-01-01" ], freq = None )
278+
279+ dtype = {"b" : CategoricalDtype (dti )}
280+
281+ data = "b\n 2017-01-01\n 2018-01-01\n 2019-01-01"
282+ expected = DataFrame ({"b" : Categorical (dtype ["b" ].categories )})
283+
284+ if parser .engine == "pyarrow" :
285+ msg = "Constructing a Categorical with a dtype and values containing"
286+ with tm .assert_produces_warning (
287+ Pandas4Warning , match = msg , check_stacklevel = False
288+ ):
289+ result = parser .read_csv (StringIO (data ), dtype = dtype )
290+ tm .assert_series_equal (
291+ result ["b" ].isna (), pd .Series ([True , True , True ], name = "b" )
292+ )
293+ else :
294+ result = parser .read_csv (StringIO (data ), dtype = dtype )
295+ tm .assert_frame_equal (result , expected )
296+
297+
275298def test_categorical_coerces_timestamp (all_parsers ):
276299 parser = all_parsers
277- dtype = {"b" : CategoricalDtype ([Timestamp ("2014-01-01 12:00:00 " )])}
300+ dtype = {"b" : CategoricalDtype ([Timestamp ("2014" )])}
278301
279- data = "b\n 2014-01-01 12:00:00 \n 2014-01-01 12:00:00 "
280- expected = DataFrame ({"b" : Categorical ([Timestamp ("2014-01-01 12:00:00 " )] * 2 )})
302+ data = "b\n 2014-01-01\n 2014-01-01"
303+ expected = DataFrame ({"b" : Categorical ([Timestamp ("2014" )] * 2 )})
281304
282- result = parser .read_csv (StringIO (data ), dtype = dtype )
283- tm .assert_frame_equal (result , expected )
305+ if parser .engine == "pyarrow" :
306+ msg = "Constructing a Categorical with a dtype and values containing"
307+ with tm .assert_produces_warning (
308+ Pandas4Warning , match = msg , check_stacklevel = False
309+ ):
310+ result = parser .read_csv (StringIO (data ), dtype = dtype )
311+ tm .assert_series_equal (result ["b" ].isna (), pd .Series ([True , True ], name = "b" ))
312+ else :
313+ result = parser .read_csv (StringIO (data ), dtype = dtype )
314+ tm .assert_frame_equal (result , expected )
284315
285316
286317def test_categorical_coerces_timedelta (all_parsers ):
0 commit comments