forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_constructors.py
2238 lines (1853 loc) · 81.3 KB
/
test_constructors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import OrderedDict
from collections.abc import Iterator
from datetime import (
datetime,
timedelta,
)
from dateutil.tz import tzoffset
import numpy as np
from numpy import ma
import pytest
from pandas._libs import (
iNaT,
lib,
)
from pandas.errors import IntCastingNaNError
import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_categorical_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
DatetimeTZDtype,
Index,
Interval,
IntervalIndex,
MultiIndex,
NaT,
Period,
RangeIndex,
Series,
Timestamp,
date_range,
isna,
period_range,
timedelta_range,
)
import pandas._testing as tm
from pandas.core.arrays import (
IntegerArray,
IntervalArray,
period_array,
)
from pandas.core.internals.blocks import NumpyBlock
class TestSeriesConstructors:
def test_from_ints_with_non_nano_dt64_dtype(self, index_or_series):
values = np.arange(10)
res = index_or_series(values, dtype="M8[s]")
expected = index_or_series(values.astype("M8[s]"))
tm.assert_equal(res, expected)
res = index_or_series(list(values), dtype="M8[s]")
tm.assert_equal(res, expected)
def test_from_na_value_and_interval_of_datetime_dtype(self):
# GH#41805
ser = Series([None], dtype="interval[datetime64[ns]]")
assert ser.isna().all()
assert ser.dtype == "interval[datetime64[ns], right]"
def test_infer_with_date_and_datetime(self):
# GH#49341 pre-2.0 we inferred datetime-and-date to datetime64, which
# was inconsistent with Index behavior
ts = Timestamp(2016, 1, 1)
vals = [ts.to_pydatetime(), ts.date()]
ser = Series(vals)
expected = Series(vals, dtype=object)
tm.assert_series_equal(ser, expected)
idx = Index(vals)
expected = Index(vals, dtype=object)
tm.assert_index_equal(idx, expected)
def test_unparsable_strings_with_dt64_dtype(self):
# pre-2.0 these would be silently ignored and come back with object dtype
vals = ["aa"]
msg = "^Unknown datetime string format, unable to parse: aa, at position 0$"
with pytest.raises(ValueError, match=msg):
Series(vals, dtype="datetime64[ns]")
with pytest.raises(ValueError, match=msg):
Series(np.array(vals, dtype=object), dtype="datetime64[ns]")
@pytest.mark.parametrize(
"constructor",
[
# NOTE: some overlap with test_constructor_empty but that test does not
# test for None or an empty generator.
# test_constructor_pass_none tests None but only with the index also
# passed.
(lambda idx: Series(index=idx)),
(lambda idx: Series(None, index=idx)),
(lambda idx: Series({}, index=idx)),
(lambda idx: Series((), index=idx)),
(lambda idx: Series([], index=idx)),
(lambda idx: Series((_ for _ in []), index=idx)),
(lambda idx: Series(data=None, index=idx)),
(lambda idx: Series(data={}, index=idx)),
(lambda idx: Series(data=(), index=idx)),
(lambda idx: Series(data=[], index=idx)),
(lambda idx: Series(data=(_ for _ in []), index=idx)),
],
)
@pytest.mark.parametrize("empty_index", [None, []])
def test_empty_constructor(self, constructor, empty_index):
# GH 49573 (addition of empty_index parameter)
expected = Series(index=empty_index)
result = constructor(empty_index)
assert result.dtype == object
assert len(result.index) == 0
tm.assert_series_equal(result, expected, check_index_type=True)
def test_invalid_dtype(self):
# GH15520
msg = "not understood"
invalid_list = [Timestamp, "Timestamp", list]
for dtype in invalid_list:
with pytest.raises(TypeError, match=msg):
Series([], name="time", dtype=dtype)
def test_invalid_compound_dtype(self):
# GH#13296
c_dtype = np.dtype([("a", "i8"), ("b", "f4")])
cdt_arr = np.array([(1, 0.4), (256, -13)], dtype=c_dtype)
with pytest.raises(ValueError, match="Use DataFrame instead"):
Series(cdt_arr, index=["A", "B"])
def test_scalar_conversion(self):
# Pass in scalar is disabled
scalar = Series(0.5)
assert not isinstance(scalar, float)
def test_scalar_extension_dtype(self, ea_scalar_and_dtype):
# GH 28401
ea_scalar, ea_dtype = ea_scalar_and_dtype
ser = Series(ea_scalar, index=range(3))
expected = Series([ea_scalar] * 3, dtype=ea_dtype)
assert ser.dtype == ea_dtype
tm.assert_series_equal(ser, expected)
def test_constructor(self, datetime_series, using_infer_string):
empty_series = Series()
assert datetime_series.index._is_all_dates
# Pass in Series
derived = Series(datetime_series)
assert derived.index._is_all_dates
assert tm.equalContents(derived.index, datetime_series.index)
# Ensure new index is not created
assert id(datetime_series.index) == id(derived.index)
# Mixed type Series
mixed = Series(["hello", np.nan], index=[0, 1])
assert mixed.dtype == np.object_ if not using_infer_string else "string"
assert np.isnan(mixed[1])
assert not empty_series.index._is_all_dates
assert not Series().index._is_all_dates
# exception raised is of type ValueError GH35744
with pytest.raises(
ValueError,
match=r"Data must be 1-dimensional, got ndarray of shape \(3, 3\) instead",
):
Series(np.random.default_rng(2).standard_normal((3, 3)), index=np.arange(3))
mixed.name = "Series"
rs = Series(mixed).name
xp = "Series"
assert rs == xp
# raise on MultiIndex GH4187
m = MultiIndex.from_arrays([[1, 2], [3, 4]])
msg = "initializing a Series from a MultiIndex is not supported"
with pytest.raises(NotImplementedError, match=msg):
Series(m)
def test_constructor_index_ndim_gt_1_raises(self):
# GH#18579
df = DataFrame([[1, 2], [3, 4], [5, 6]], index=[3, 6, 9])
with pytest.raises(ValueError, match="Index data must be 1-dimensional"):
Series([1, 3, 2], index=df)
@pytest.mark.parametrize("input_class", [list, dict, OrderedDict])
def test_constructor_empty(self, input_class, using_infer_string):
empty = Series()
empty2 = Series(input_class())
# these are Index() and RangeIndex() which don't compare type equal
# but are just .equals
tm.assert_series_equal(empty, empty2, check_index_type=False)
# With explicit dtype:
empty = Series(dtype="float64")
empty2 = Series(input_class(), dtype="float64")
tm.assert_series_equal(empty, empty2, check_index_type=False)
# GH 18515 : with dtype=category:
empty = Series(dtype="category")
empty2 = Series(input_class(), dtype="category")
tm.assert_series_equal(empty, empty2, check_index_type=False)
if input_class is not list:
# With index:
empty = Series(index=range(10))
empty2 = Series(input_class(), index=range(10))
tm.assert_series_equal(empty, empty2)
# With index and dtype float64:
empty = Series(np.nan, index=range(10))
empty2 = Series(input_class(), index=range(10), dtype="float64")
tm.assert_series_equal(empty, empty2)
# GH 19853 : with empty string, index and dtype str
empty = Series("", dtype=str, index=range(3))
if using_infer_string:
empty2 = Series("", index=range(3), dtype=object)
else:
empty2 = Series("", index=range(3))
tm.assert_series_equal(empty, empty2)
@pytest.mark.parametrize("input_arg", [np.nan, float("nan")])
def test_constructor_nan(self, input_arg):
empty = Series(dtype="float64", index=range(10))
empty2 = Series(input_arg, index=range(10))
tm.assert_series_equal(empty, empty2, check_index_type=False)
@pytest.mark.parametrize(
"dtype",
["f8", "i8", "M8[ns]", "m8[ns]", "category", "object", "datetime64[ns, UTC]"],
)
@pytest.mark.parametrize("index", [None, Index([])])
def test_constructor_dtype_only(self, dtype, index):
# GH-20865
result = Series(dtype=dtype, index=index)
assert result.dtype == dtype
assert len(result) == 0
def test_constructor_no_data_index_order(self):
result = Series(index=["b", "a", "c"])
assert result.index.tolist() == ["b", "a", "c"]
def test_constructor_no_data_string_type(self):
# GH 22477
result = Series(index=[1], dtype=str)
assert np.isnan(result.iloc[0])
@pytest.mark.parametrize("item", ["entry", "ѐ", 13])
def test_constructor_string_element_string_type(self, item):
# GH 22477
result = Series(item, index=[1], dtype=str)
assert result.iloc[0] == str(item)
def test_constructor_dtype_str_na_values(self, string_dtype):
# https://github.com/pandas-dev/pandas/issues/21083
ser = Series(["x", None], dtype=string_dtype)
result = ser.isna()
expected = Series([False, True])
tm.assert_series_equal(result, expected)
assert ser.iloc[1] is None
ser = Series(["x", np.nan], dtype=string_dtype)
assert np.isnan(ser.iloc[1])
def test_constructor_series(self):
index1 = ["d", "b", "a", "c"]
index2 = sorted(index1)
s1 = Series([4, 7, -5, 3], index=index1)
s2 = Series(s1, index=index2)
tm.assert_series_equal(s2, s1.sort_index())
def test_constructor_iterable(self):
# GH 21987
class Iter:
def __iter__(self) -> Iterator:
yield from range(10)
expected = Series(list(range(10)), dtype="int64")
result = Series(Iter(), dtype="int64")
tm.assert_series_equal(result, expected)
def test_constructor_sequence(self):
# GH 21987
expected = Series(list(range(10)), dtype="int64")
result = Series(range(10), dtype="int64")
tm.assert_series_equal(result, expected)
def test_constructor_single_str(self):
# GH 21987
expected = Series(["abc"])
result = Series("abc")
tm.assert_series_equal(result, expected)
def test_constructor_list_like(self):
# make sure that we are coercing different
# list-likes to standard dtypes and not
# platform specific
expected = Series([1, 2, 3], dtype="int64")
for obj in [[1, 2, 3], (1, 2, 3), np.array([1, 2, 3], dtype="int64")]:
result = Series(obj, index=[0, 1, 2])
tm.assert_series_equal(result, expected)
def test_constructor_boolean_index(self):
# GH#18579
s1 = Series([1, 2, 3], index=[4, 5, 6])
index = s1 == 2
result = Series([1, 3, 2], index=index)
expected = Series([1, 3, 2], index=[False, True, False])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("dtype", ["bool", "int32", "int64", "float64"])
def test_constructor_index_dtype(self, dtype):
# GH 17088
s = Series(Index([0, 2, 4]), dtype=dtype)
assert s.dtype == dtype
@pytest.mark.parametrize(
"input_vals",
[
([1, 2]),
(["1", "2"]),
(list(date_range("1/1/2011", periods=2, freq="h"))),
(list(date_range("1/1/2011", periods=2, freq="h", tz="US/Eastern"))),
([Interval(left=0, right=5)]),
],
)
def test_constructor_list_str(self, input_vals, string_dtype):
# GH 16605
# Ensure that data elements from a list are converted to strings
# when dtype is str, 'str', or 'U'
result = Series(input_vals, dtype=string_dtype)
expected = Series(input_vals).astype(string_dtype)
tm.assert_series_equal(result, expected)
def test_constructor_list_str_na(self, string_dtype):
result = Series([1.0, 2.0, np.nan], dtype=string_dtype)
expected = Series(["1.0", "2.0", np.nan], dtype=object)
tm.assert_series_equal(result, expected)
assert np.isnan(result[2])
def test_constructor_generator(self):
gen = (i for i in range(10))
result = Series(gen)
exp = Series(range(10))
tm.assert_series_equal(result, exp)
# same but with non-default index
gen = (i for i in range(10))
result = Series(gen, index=range(10, 20))
exp.index = range(10, 20)
tm.assert_series_equal(result, exp)
def test_constructor_map(self):
# GH8909
m = (x for x in range(10))
result = Series(m)
exp = Series(range(10))
tm.assert_series_equal(result, exp)
# same but with non-default index
m = (x for x in range(10))
result = Series(m, index=range(10, 20))
exp.index = range(10, 20)
tm.assert_series_equal(result, exp)
def test_constructor_categorical(self):
cat = Categorical([0, 1, 2, 0, 1, 2], ["a", "b", "c"])
res = Series(cat)
tm.assert_categorical_equal(res.values, cat)
# can cast to a new dtype
result = Series(Categorical([1, 2, 3]), dtype="int64")
expected = Series([1, 2, 3], dtype="int64")
tm.assert_series_equal(result, expected)
def test_construct_from_categorical_with_dtype(self):
# GH12574
cat = Series(Categorical([1, 2, 3]), dtype="category")
msg = "is_categorical_dtype is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
assert is_categorical_dtype(cat)
assert is_categorical_dtype(cat.dtype)
def test_construct_intlist_values_category_dtype(self):
ser = Series([1, 2, 3], dtype="category")
msg = "is_categorical_dtype is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
assert is_categorical_dtype(ser)
assert is_categorical_dtype(ser.dtype)
def test_constructor_categorical_with_coercion(self):
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])
# test basic creation / coercion of categoricals
s = Series(factor, name="A")
assert s.dtype == "category"
assert len(s) == len(factor)
# in a frame
df = DataFrame({"A": factor})
result = df["A"]
tm.assert_series_equal(result, s)
result = df.iloc[:, 0]
tm.assert_series_equal(result, s)
assert len(df) == len(factor)
df = DataFrame({"A": s})
result = df["A"]
tm.assert_series_equal(result, s)
assert len(df) == len(factor)
# multiples
df = DataFrame({"A": s, "B": s, "C": 1})
result1 = df["A"]
result2 = df["B"]
tm.assert_series_equal(result1, s)
tm.assert_series_equal(result2, s, check_names=False)
assert result2.name == "B"
assert len(df) == len(factor)
def test_constructor_categorical_with_coercion2(self):
# GH8623
x = DataFrame(
[[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]],
columns=["person_id", "person_name"],
)
x["person_name"] = Categorical(x.person_name) # doing this breaks transform
expected = x.iloc[0].person_name
result = x.person_name.iloc[0]
assert result == expected
result = x.person_name[0]
assert result == expected
result = x.person_name.loc[0]
assert result == expected
def test_constructor_series_to_categorical(self):
# see GH#16524: test conversion of Series to Categorical
series = Series(["a", "b", "c"])
result = Series(series, dtype="category")
expected = Series(["a", "b", "c"], dtype="category")
tm.assert_series_equal(result, expected)
def test_constructor_categorical_dtype(self):
result = Series(
["a", "b"], dtype=CategoricalDtype(["a", "b", "c"], ordered=True)
)
assert isinstance(result.dtype, CategoricalDtype)
tm.assert_index_equal(result.cat.categories, Index(["a", "b", "c"]))
assert result.cat.ordered
result = Series(["a", "b"], dtype=CategoricalDtype(["b", "a"]))
assert isinstance(result.dtype, CategoricalDtype)
tm.assert_index_equal(result.cat.categories, Index(["b", "a"]))
assert result.cat.ordered is False
# GH 19565 - Check broadcasting of scalar with Categorical dtype
result = Series(
"a", index=[0, 1], dtype=CategoricalDtype(["a", "b"], ordered=True)
)
expected = Series(
["a", "a"], index=[0, 1], dtype=CategoricalDtype(["a", "b"], ordered=True)
)
tm.assert_series_equal(result, expected)
def test_constructor_categorical_string(self):
# GH 26336: the string 'category' maintains existing CategoricalDtype
cdt = CategoricalDtype(categories=list("dabc"), ordered=True)
expected = Series(list("abcabc"), dtype=cdt)
# Series(Categorical, dtype='category') keeps existing dtype
cat = Categorical(list("abcabc"), dtype=cdt)
result = Series(cat, dtype="category")
tm.assert_series_equal(result, expected)
# Series(Series[Categorical], dtype='category') keeps existing dtype
result = Series(result, dtype="category")
tm.assert_series_equal(result, expected)
def test_categorical_sideeffects_free(self):
# Passing a categorical to a Series and then changing values in either
# the series or the categorical should not change the values in the
# other one, IF you specify copy!
cat = Categorical(["a", "b", "c", "a"])
s = Series(cat, copy=True)
assert s.cat is not cat
s = s.cat.rename_categories([1, 2, 3])
exp_s = np.array([1, 2, 3, 1], dtype=np.int64)
exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_)
tm.assert_numpy_array_equal(s.__array__(), exp_s)
tm.assert_numpy_array_equal(cat.__array__(), exp_cat)
# setting
s[0] = 2
exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64)
tm.assert_numpy_array_equal(s.__array__(), exp_s2)
tm.assert_numpy_array_equal(cat.__array__(), exp_cat)
# however, copy is False by default
# so this WILL change values
cat = Categorical(["a", "b", "c", "a"])
s = Series(cat, copy=False)
assert s.values is cat
s = s.cat.rename_categories([1, 2, 3])
assert s.values is not cat
exp_s = np.array([1, 2, 3, 1], dtype=np.int64)
tm.assert_numpy_array_equal(s.__array__(), exp_s)
s[0] = 2
exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64)
tm.assert_numpy_array_equal(s.__array__(), exp_s2)
def test_unordered_compare_equal(self):
left = Series(["a", "b", "c"], dtype=CategoricalDtype(["a", "b"]))
right = Series(Categorical(["a", "b", np.nan], categories=["a", "b"]))
tm.assert_series_equal(left, right)
def test_constructor_maskedarray(self):
data = ma.masked_all((3,), dtype=float)
result = Series(data)
expected = Series([np.nan, np.nan, np.nan])
tm.assert_series_equal(result, expected)
data[0] = 0.0
data[2] = 2.0
index = ["a", "b", "c"]
result = Series(data, index=index)
expected = Series([0.0, np.nan, 2.0], index=index)
tm.assert_series_equal(result, expected)
data[1] = 1.0
result = Series(data, index=index)
expected = Series([0.0, 1.0, 2.0], index=index)
tm.assert_series_equal(result, expected)
data = ma.masked_all((3,), dtype=int)
result = Series(data)
expected = Series([np.nan, np.nan, np.nan], dtype=float)
tm.assert_series_equal(result, expected)
data[0] = 0
data[2] = 2
index = ["a", "b", "c"]
result = Series(data, index=index)
expected = Series([0, np.nan, 2], index=index, dtype=float)
tm.assert_series_equal(result, expected)
data[1] = 1
result = Series(data, index=index)
expected = Series([0, 1, 2], index=index, dtype=int)
tm.assert_series_equal(result, expected)
data = ma.masked_all((3,), dtype=bool)
result = Series(data)
expected = Series([np.nan, np.nan, np.nan], dtype=object)
tm.assert_series_equal(result, expected)
data[0] = True
data[2] = False
index = ["a", "b", "c"]
result = Series(data, index=index)
expected = Series([True, np.nan, False], index=index, dtype=object)
tm.assert_series_equal(result, expected)
data[1] = True
result = Series(data, index=index)
expected = Series([True, True, False], index=index, dtype=bool)
tm.assert_series_equal(result, expected)
data = ma.masked_all((3,), dtype="M8[ns]")
result = Series(data)
expected = Series([iNaT, iNaT, iNaT], dtype="M8[ns]")
tm.assert_series_equal(result, expected)
data[0] = datetime(2001, 1, 1)
data[2] = datetime(2001, 1, 3)
index = ["a", "b", "c"]
result = Series(data, index=index)
expected = Series(
[datetime(2001, 1, 1), iNaT, datetime(2001, 1, 3)],
index=index,
dtype="M8[ns]",
)
tm.assert_series_equal(result, expected)
data[1] = datetime(2001, 1, 2)
result = Series(data, index=index)
expected = Series(
[datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 3)],
index=index,
dtype="M8[ns]",
)
tm.assert_series_equal(result, expected)
def test_constructor_maskedarray_hardened(self):
# Check numpy masked arrays with hard masks -- from GH24574
data = ma.masked_all((3,), dtype=float).harden_mask()
result = Series(data)
expected = Series([np.nan, np.nan, np.nan])
tm.assert_series_equal(result, expected)
def test_series_ctor_plus_datetimeindex(self, using_copy_on_write):
rng = date_range("20090415", "20090519", freq="B")
data = {k: 1 for k in rng}
result = Series(data, index=rng)
if using_copy_on_write:
assert result.index.is_(rng)
else:
assert result.index is rng
def test_constructor_default_index(self):
s = Series([0, 1, 2])
tm.assert_index_equal(s.index, Index(range(3)), exact=True)
@pytest.mark.parametrize(
"input",
[
[1, 2, 3],
(1, 2, 3),
list(range(3)),
Categorical(["a", "b", "a"]),
(i for i in range(3)),
(x for x in range(3)),
],
)
def test_constructor_index_mismatch(self, input):
# GH 19342
# test that construction of a Series with an index of different length
# raises an error
msg = r"Length of values \(3\) does not match length of index \(4\)"
with pytest.raises(ValueError, match=msg):
Series(input, index=np.arange(4))
def test_constructor_numpy_scalar(self):
# GH 19342
# construction with a numpy scalar
# should not raise
result = Series(np.array(100), index=np.arange(4), dtype="int64")
expected = Series(100, index=np.arange(4), dtype="int64")
tm.assert_series_equal(result, expected)
def test_constructor_broadcast_list(self):
# GH 19342
# construction with single-element container and index
# should raise
msg = r"Length of values \(1\) does not match length of index \(3\)"
with pytest.raises(ValueError, match=msg):
Series(["foo"], index=["a", "b", "c"])
def test_constructor_corner(self):
df = tm.makeTimeDataFrame()
objs = [df, df]
s = Series(objs, index=[0, 1])
assert isinstance(s, Series)
def test_constructor_sanitize(self):
s = Series(np.array([1.0, 1.0, 8.0]), dtype="i8")
assert s.dtype == np.dtype("i8")
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
with pytest.raises(IntCastingNaNError, match=msg):
Series(np.array([1.0, 1.0, np.nan]), copy=True, dtype="i8")
def test_constructor_copy(self):
# GH15125
# test dtype parameter has no side effects on copy=True
for data in [[1.0], np.array([1.0])]:
x = Series(data)
y = Series(x, copy=True, dtype=float)
# copy=True maintains original data in Series
tm.assert_series_equal(x, y)
# changes to origin of copy does not affect the copy
x[0] = 2.0
assert not x.equals(y)
assert x[0] == 2.0
assert y[0] == 1.0
@td.skip_array_manager_invalid_test # TODO(ArrayManager) rewrite test
@pytest.mark.parametrize(
"index",
[
date_range("20170101", periods=3, tz="US/Eastern"),
date_range("20170101", periods=3),
timedelta_range("1 day", periods=3),
period_range("2012Q1", periods=3, freq="Q"),
Index(list("abc")),
Index([1, 2, 3]),
RangeIndex(0, 3),
],
ids=lambda x: type(x).__name__,
)
def test_constructor_limit_copies(self, index):
# GH 17449
# limit copies of input
s = Series(index)
# we make 1 copy; this is just a smoke test here
assert s._mgr.blocks[0].values is not index
def test_constructor_shallow_copy(self):
# constructing a Series from Series with copy=False should still
# give a "shallow" copy (share data, not attributes)
# https://github.com/pandas-dev/pandas/issues/49523
s = Series([1, 2, 3])
s_orig = s.copy()
s2 = Series(s)
assert s2._mgr is not s._mgr
# Overwriting index of s2 doesn't change s
s2.index = ["a", "b", "c"]
tm.assert_series_equal(s, s_orig)
def test_constructor_pass_none(self):
s = Series(None, index=range(5))
assert s.dtype == np.float64
s = Series(None, index=range(5), dtype=object)
assert s.dtype == np.object_
# GH 7431
# inference on the index
s = Series(index=np.array([None]))
expected = Series(index=Index([None]))
tm.assert_series_equal(s, expected)
def test_constructor_pass_nan_nat(self):
# GH 13467
exp = Series([np.nan, np.nan], dtype=np.float64)
assert exp.dtype == np.float64
tm.assert_series_equal(Series([np.nan, np.nan]), exp)
tm.assert_series_equal(Series(np.array([np.nan, np.nan])), exp)
exp = Series([NaT, NaT])
assert exp.dtype == "datetime64[ns]"
tm.assert_series_equal(Series([NaT, NaT]), exp)
tm.assert_series_equal(Series(np.array([NaT, NaT])), exp)
tm.assert_series_equal(Series([NaT, np.nan]), exp)
tm.assert_series_equal(Series(np.array([NaT, np.nan])), exp)
tm.assert_series_equal(Series([np.nan, NaT]), exp)
tm.assert_series_equal(Series(np.array([np.nan, NaT])), exp)
def test_constructor_cast(self):
msg = "could not convert string to float"
with pytest.raises(ValueError, match=msg):
Series(["a", "b", "c"], dtype=float)
def test_constructor_signed_int_overflow_raises(self):
# GH#41734 disallow silent overflow, enforced in 2.0
msg = "Values are too large to be losslessly converted"
with pytest.raises(ValueError, match=msg):
Series([1, 200, 923442], dtype="int8")
with pytest.raises(ValueError, match=msg):
Series([1, 200, 923442], dtype="uint8")
@pytest.mark.parametrize(
"values",
[
np.array([1], dtype=np.uint16),
np.array([1], dtype=np.uint32),
np.array([1], dtype=np.uint64),
[np.uint16(1)],
[np.uint32(1)],
[np.uint64(1)],
],
)
def test_constructor_numpy_uints(self, values):
# GH#47294
value = values[0]
result = Series(values)
assert result[0].dtype == value.dtype
assert result[0] == value
def test_constructor_unsigned_dtype_overflow(self, any_unsigned_int_numpy_dtype):
# see gh-15832
msg = "Trying to coerce negative values to unsigned integers"
with pytest.raises(OverflowError, match=msg):
Series([-1], dtype=any_unsigned_int_numpy_dtype)
def test_constructor_floating_data_int_dtype(self, frame_or_series):
# GH#40110
arr = np.random.default_rng(2).standard_normal(2)
# Long-standing behavior (for Series, new in 2.0 for DataFrame)
# has been to ignore the dtype on these;
# not clear if this is what we want long-term
# expected = frame_or_series(arr)
# GH#49599 as of 2.0 we raise instead of silently retaining float dtype
msg = "Trying to coerce float values to integer"
with pytest.raises(ValueError, match=msg):
frame_or_series(arr, dtype="i8")
with pytest.raises(ValueError, match=msg):
frame_or_series(list(arr), dtype="i8")
# pre-2.0, when we had NaNs, we silently ignored the integer dtype
arr[0] = np.nan
# expected = frame_or_series(arr)
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
with pytest.raises(IntCastingNaNError, match=msg):
frame_or_series(arr, dtype="i8")
exc = IntCastingNaNError
if frame_or_series is Series:
# TODO: try to align these
exc = ValueError
msg = "cannot convert float NaN to integer"
with pytest.raises(exc, match=msg):
# same behavior if we pass list instead of the ndarray
frame_or_series(list(arr), dtype="i8")
# float array that can be losslessly cast to integers
arr = np.array([1.0, 2.0], dtype="float64")
expected = frame_or_series(arr.astype("i8"))
obj = frame_or_series(arr, dtype="i8")
tm.assert_equal(obj, expected)
obj = frame_or_series(list(arr), dtype="i8")
tm.assert_equal(obj, expected)
def test_constructor_coerce_float_fail(self, any_int_numpy_dtype):
# see gh-15832
# Updated: make sure we treat this list the same as we would treat
# the equivalent ndarray
# GH#49599 pre-2.0 we silently retained float dtype, in 2.0 we raise
vals = [1, 2, 3.5]
msg = "Trying to coerce float values to integer"
with pytest.raises(ValueError, match=msg):
Series(vals, dtype=any_int_numpy_dtype)
with pytest.raises(ValueError, match=msg):
Series(np.array(vals), dtype=any_int_numpy_dtype)
def test_constructor_coerce_float_valid(self, float_numpy_dtype):
s = Series([1, 2, 3.5], dtype=float_numpy_dtype)
expected = Series([1, 2, 3.5]).astype(float_numpy_dtype)
tm.assert_series_equal(s, expected)
def test_constructor_invalid_coerce_ints_with_float_nan(self, any_int_numpy_dtype):
# GH 22585
# Updated: make sure we treat this list the same as we would treat the
# equivalent ndarray
vals = [1, 2, np.nan]
# pre-2.0 this would return with a float dtype, in 2.0 we raise
msg = "cannot convert float NaN to integer"
with pytest.raises(ValueError, match=msg):
Series(vals, dtype=any_int_numpy_dtype)
msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
with pytest.raises(IntCastingNaNError, match=msg):
Series(np.array(vals), dtype=any_int_numpy_dtype)
def test_constructor_dtype_no_cast(self, using_copy_on_write, warn_copy_on_write):
# see gh-1572
s = Series([1, 2, 3])
s2 = Series(s, dtype=np.int64)
warn = FutureWarning if warn_copy_on_write else None
with tm.assert_produces_warning(warn):
s2[1] = 5
if using_copy_on_write:
assert s[1] == 2
else:
assert s[1] == 5
def test_constructor_datelike_coercion(self):
# GH 9477
# incorrectly inferring on dateimelike looking when object dtype is
# specified
s = Series([Timestamp("20130101"), "NOV"], dtype=object)
assert s.iloc[0] == Timestamp("20130101")
assert s.iloc[1] == "NOV"
assert s.dtype == object
def test_constructor_datelike_coercion2(self):
# the dtype was being reset on the slicing and re-inferred to datetime
# even thought the blocks are mixed
belly = "216 3T19".split()
wing1 = "2T15 4H19".split()
wing2 = "416 4T20".split()
mat = pd.to_datetime("2016-01-22 2019-09-07".split())
df = DataFrame({"wing1": wing1, "wing2": wing2, "mat": mat}, index=belly)
result = df.loc["3T19"]
assert result.dtype == object
result = df.loc["216"]
assert result.dtype == object
def test_constructor_mixed_int_and_timestamp(self, frame_or_series):
# specifically Timestamp with nanos, not datetimes
objs = [Timestamp(9), 10, NaT._value]
result = frame_or_series(objs, dtype="M8[ns]")
expected = frame_or_series([Timestamp(9), Timestamp(10), NaT])
tm.assert_equal(result, expected)
def test_constructor_datetimes_with_nulls(self):
# gh-15869
for arr in [
np.array([None, None, None, None, datetime.now(), None]),
np.array([None, None, datetime.now(), None]),
]:
result = Series(arr)
assert result.dtype == "M8[ns]"
def test_constructor_dtype_datetime64(self):
s = Series(iNaT, dtype="M8[ns]", index=range(5))
assert isna(s).all()
# in theory this should be all nulls, but since
# we are not specifying a dtype is ambiguous
s = Series(iNaT, index=range(5))
assert not isna(s).all()
s = Series(np.nan, dtype="M8[ns]", index=range(5))
assert isna(s).all()
s = Series([datetime(2001, 1, 2, 0, 0), iNaT], dtype="M8[ns]")
assert isna(s[1])
assert s.dtype == "M8[ns]"
s = Series([datetime(2001, 1, 2, 0, 0), np.nan], dtype="M8[ns]")
assert isna(s[1])
assert s.dtype == "M8[ns]"
def test_constructor_dtype_datetime64_10(self):
# GH3416
pydates = [datetime(2013, 1, 1), datetime(2013, 1, 2), datetime(2013, 1, 3)]
dates = [np.datetime64(x) for x in pydates]
ser = Series(dates)
assert ser.dtype == "M8[ns]"
ser.iloc[0] = np.nan
assert ser.dtype == "M8[ns]"
# GH3414 related
expected = Series(pydates, dtype="datetime64[ms]")
result = Series(Series(dates).astype(np.int64) / 1000000, dtype="M8[ms]")
tm.assert_series_equal(result, expected)
result = Series(dates, dtype="datetime64[ms]")
tm.assert_series_equal(result, expected)
expected = Series(
[NaT, datetime(2013, 1, 2), datetime(2013, 1, 3)], dtype="datetime64[ns]"
)
result = Series([np.nan] + dates[1:], dtype="datetime64[ns]")
tm.assert_series_equal(result, expected)
def test_constructor_dtype_datetime64_11(self):
pydates = [datetime(2013, 1, 1), datetime(2013, 1, 2), datetime(2013, 1, 3)]
dates = [np.datetime64(x) for x in pydates]
dts = Series(dates, dtype="datetime64[ns]")
# valid astype
dts.astype("int64")
# invalid casting
msg = r"Converting from datetime64\[ns\] to int32 is not supported"
with pytest.raises(TypeError, match=msg):
dts.astype("int32")
# ints are ok
# we test with np.int64 to get similar results on
# windows / 32-bit platforms