forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_stata.py
2603 lines (2277 loc) · 97.4 KB
/
test_stata.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
import bz2
import datetime as dt
from datetime import datetime
import gzip
import io
import itertools
import os
import string
import struct
import tarfile
import zipfile
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import CategoricalDtype
import pandas._testing as tm
from pandas.core.frame import (
DataFrame,
Series,
)
from pandas.io.parsers import read_csv
from pandas.io.stata import (
CategoricalConversionWarning,
InvalidColumnName,
PossiblePrecisionLoss,
StataMissingValue,
StataReader,
StataWriter,
StataWriterUTF8,
ValueLabelTypeMismatch,
read_stata,
)
@pytest.fixture
def mixed_frame():
return DataFrame(
{
"a": [1, 2, 3, 4],
"b": [1.0, 3.0, 27.0, 81.0],
"c": ["Atlanta", "Birmingham", "Cincinnati", "Detroit"],
}
)
@pytest.fixture
def parsed_114(datapath):
dta14_114 = datapath("io", "data", "stata", "stata5_114.dta")
parsed_114 = read_stata(dta14_114, convert_dates=True)
parsed_114.index.name = "index"
return parsed_114
class TestStata:
def read_dta(self, file):
# Legacy default reader configuration
return read_stata(file, convert_dates=True)
def read_csv(self, file):
return read_csv(file, parse_dates=True)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_empty_dta(self, version, temp_file):
empty_ds = DataFrame(columns=["unit"])
# GH 7369, make sure can read a 0-obs dta file
path = temp_file
empty_ds.to_stata(path, write_index=False, version=version)
empty_ds2 = read_stata(path)
tm.assert_frame_equal(empty_ds, empty_ds2)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_empty_dta_with_dtypes(self, version, temp_file):
# GH 46240
# Fixing above bug revealed that types are not correctly preserved when
# writing empty DataFrames
empty_df_typed = DataFrame(
{
"i8": np.array([0], dtype=np.int8),
"i16": np.array([0], dtype=np.int16),
"i32": np.array([0], dtype=np.int32),
"i64": np.array([0], dtype=np.int64),
"u8": np.array([0], dtype=np.uint8),
"u16": np.array([0], dtype=np.uint16),
"u32": np.array([0], dtype=np.uint32),
"u64": np.array([0], dtype=np.uint64),
"f32": np.array([0], dtype=np.float32),
"f64": np.array([0], dtype=np.float64),
}
)
# GH 7369, make sure can read a 0-obs dta file
path = temp_file
empty_df_typed.to_stata(path, write_index=False, version=version)
empty_reread = read_stata(path)
expected = empty_df_typed
# No uint# support. Downcast since values in range for int#
expected["u8"] = expected["u8"].astype(np.int8)
expected["u16"] = expected["u16"].astype(np.int16)
expected["u32"] = expected["u32"].astype(np.int32)
# No int64 supported at all. Downcast since values in range for int32
expected["u64"] = expected["u64"].astype(np.int32)
expected["i64"] = expected["i64"].astype(np.int32)
tm.assert_frame_equal(expected, empty_reread)
tm.assert_series_equal(expected.dtypes, empty_reread.dtypes)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_index_col_none(self, version, temp_file):
df = DataFrame({"a": range(5), "b": ["b1", "b2", "b3", "b4", "b5"]})
# GH 7369, make sure can read a 0-obs dta file
path = temp_file
df.to_stata(path, write_index=False, version=version)
read_df = read_stata(path)
assert isinstance(read_df.index, pd.RangeIndex)
expected = df
expected["a"] = expected["a"].astype(np.int32)
tm.assert_frame_equal(read_df, expected, check_index_type=True)
@pytest.mark.parametrize(
"version", [102, 103, 104, 105, 108, 110, 111, 113, 114, 115, 117, 118, 119]
)
def test_read_dta1(self, version, datapath):
file = datapath("io", "data", "stata", f"stata1_{version}.dta")
parsed = self.read_dta(file)
# Pandas uses np.nan as missing value.
# Thus, all columns will be of type float, regardless of their name.
expected = DataFrame(
[(np.nan, np.nan, np.nan, np.nan, np.nan)],
columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],
)
# this is an oddity as really the nan should be float64, but
# the casting doesn't fail so need to match stata here
expected["float_miss"] = expected["float_miss"].astype(np.float32)
# Column names too long for older Stata formats
if version <= 108:
expected = expected.rename(
columns={
"float_miss": "f_miss",
"double_miss": "d_miss",
"byte_miss": "b_miss",
"int_miss": "i_miss",
"long_miss": "l_miss",
}
)
tm.assert_frame_equal(parsed, expected)
def test_read_dta2(self, datapath):
expected = DataFrame.from_records(
[
(
datetime(2006, 11, 19, 23, 13, 20),
1479596223000,
datetime(2010, 1, 20),
datetime(2010, 1, 8),
datetime(2010, 1, 1),
datetime(1974, 7, 1),
datetime(2010, 1, 1),
datetime(2010, 1, 1),
),
(
datetime(1959, 12, 31, 20, 3, 20),
-1479590,
datetime(1953, 10, 2),
datetime(1948, 6, 10),
datetime(1955, 1, 1),
datetime(1955, 7, 1),
datetime(1955, 1, 1),
datetime(2, 1, 1),
),
(pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT, pd.NaT),
],
columns=[
"datetime_c",
"datetime_big_c",
"date",
"weekly_date",
"monthly_date",
"quarterly_date",
"half_yearly_date",
"yearly_date",
],
)
# TODO(GH#55564): just pass M8[s] to the constructor
expected["datetime_c"] = expected["datetime_c"].astype("M8[ms]")
expected["date"] = expected["date"].astype("M8[s]")
expected["weekly_date"] = expected["weekly_date"].astype("M8[s]")
expected["monthly_date"] = expected["monthly_date"].astype("M8[s]")
expected["quarterly_date"] = expected["quarterly_date"].astype("M8[s]")
expected["half_yearly_date"] = expected["half_yearly_date"].astype("M8[s]")
expected["yearly_date"] = expected["yearly_date"].astype("M8[s]")
path1 = datapath("io", "data", "stata", "stata2_114.dta")
path2 = datapath("io", "data", "stata", "stata2_115.dta")
path3 = datapath("io", "data", "stata", "stata2_117.dta")
msg = "Leaving in Stata Internal Format"
with tm.assert_produces_warning(UserWarning, match=msg):
parsed_114 = self.read_dta(path1)
with tm.assert_produces_warning(UserWarning, match=msg):
parsed_115 = self.read_dta(path2)
with tm.assert_produces_warning(UserWarning, match=msg):
parsed_117 = self.read_dta(path3)
# FIXME: don't leave commented-out
# 113 is buggy due to limits of date format support in Stata
# parsed_113 = self.read_dta(
# datapath("io", "data", "stata", "stata2_113.dta")
# )
# FIXME: don't leave commented-out
# buggy test because of the NaT comparison on certain platforms
# Format 113 test fails since it does not support tc and tC formats
# tm.assert_frame_equal(parsed_113, expected)
tm.assert_frame_equal(parsed_114, expected)
tm.assert_frame_equal(parsed_115, expected)
tm.assert_frame_equal(parsed_117, expected)
@pytest.mark.parametrize(
"file", ["stata3_113", "stata3_114", "stata3_115", "stata3_117"]
)
def test_read_dta3(self, file, datapath):
file = datapath("io", "data", "stata", f"{file}.dta")
parsed = self.read_dta(file)
# match stata here
expected = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))
expected = expected.astype(np.float32)
expected["year"] = expected["year"].astype(np.int16)
expected["quarter"] = expected["quarter"].astype(np.int8)
tm.assert_frame_equal(parsed, expected)
@pytest.mark.parametrize("version", [110, 111, 113, 114, 115, 117])
def test_read_dta4(self, version, datapath):
file = datapath("io", "data", "stata", f"stata4_{version}.dta")
parsed = self.read_dta(file)
expected = DataFrame.from_records(
[
["one", "ten", "one", "one", "one"],
["two", "nine", "two", "two", "two"],
["three", "eight", "three", "three", "three"],
["four", "seven", 4, "four", "four"],
["five", "six", 5, np.nan, "five"],
["six", "five", 6, np.nan, "six"],
["seven", "four", 7, np.nan, "seven"],
["eight", "three", 8, np.nan, "eight"],
["nine", "two", 9, np.nan, "nine"],
["ten", "one", "ten", np.nan, "ten"],
],
columns=[
"fully_labeled",
"fully_labeled2",
"incompletely_labeled",
"labeled_with_missings",
"float_labelled",
],
)
# these are all categoricals
for col in expected:
orig = expected[col].copy()
categories = np.asarray(expected["fully_labeled"][orig.notna()])
if col == "incompletely_labeled":
categories = orig
cat = orig.astype("category")._values
cat = cat.set_categories(categories, ordered=True)
cat.categories.rename(None, inplace=True)
expected[col] = cat
# stata doesn't save .category metadata
tm.assert_frame_equal(parsed, expected)
@pytest.mark.parametrize("version", [102, 103, 104, 105, 108])
def test_readold_dta4(self, version, datapath):
# This test is the same as test_read_dta4 above except that the columns
# had to be renamed to match the restrictions in older file format
file = datapath("io", "data", "stata", f"stata4_{version}.dta")
parsed = self.read_dta(file)
expected = DataFrame.from_records(
[
["one", "ten", "one", "one", "one"],
["two", "nine", "two", "two", "two"],
["three", "eight", "three", "three", "three"],
["four", "seven", 4, "four", "four"],
["five", "six", 5, np.nan, "five"],
["six", "five", 6, np.nan, "six"],
["seven", "four", 7, np.nan, "seven"],
["eight", "three", 8, np.nan, "eight"],
["nine", "two", 9, np.nan, "nine"],
["ten", "one", "ten", np.nan, "ten"],
],
columns=[
"fulllab",
"fulllab2",
"incmplab",
"misslab",
"floatlab",
],
)
# these are all categoricals
for col in expected:
orig = expected[col].copy()
categories = np.asarray(expected["fulllab"][orig.notna()])
if col == "incmplab":
categories = orig
cat = orig.astype("category")._values
cat = cat.set_categories(categories, ordered=True)
cat.categories.rename(None, inplace=True)
expected[col] = cat
# stata doesn't save .category metadata
tm.assert_frame_equal(parsed, expected)
# File containing strls
@pytest.mark.parametrize(
"file",
[
"stata12_117",
"stata12_be_117",
"stata12_118",
"stata12_be_118",
"stata12_119",
"stata12_be_119",
],
)
def test_read_dta_strl(self, file, datapath):
parsed = self.read_dta(datapath("io", "data", "stata", f"{file}.dta"))
expected = DataFrame.from_records(
[
[1, "abc", "abcdefghi"],
[3, "cba", "qwertywertyqwerty"],
[93, "", "strl"],
],
columns=["x", "y", "z"],
)
tm.assert_frame_equal(parsed, expected, check_dtype=False)
# 117 is not included in this list as it uses ASCII strings
@pytest.mark.parametrize(
"file",
[
"stata14_118",
"stata14_be_118",
"stata14_119",
"stata14_be_119",
],
)
def test_read_dta118_119(self, file, datapath):
parsed_118 = self.read_dta(datapath("io", "data", "stata", f"{file}.dta"))
parsed_118["Bytes"] = parsed_118["Bytes"].astype("O")
expected = DataFrame.from_records(
[
["Cat", "Bogota", "Bogotá", 1, 1.0, "option b Ünicode", 1.0],
["Dog", "Boston", "Uzunköprü", np.nan, np.nan, np.nan, np.nan],
["Plane", "Rome", "Tromsø", 0, 0.0, "option a", 0.0],
["Potato", "Tokyo", "Elâzığ", -4, 4.0, 4, 4], # noqa: RUF001
["", "", "", 0, 0.3332999, "option a", 1 / 3.0],
],
columns=[
"Things",
"Cities",
"Unicode_Cities_Strl",
"Ints",
"Floats",
"Bytes",
"Longs",
],
)
expected["Floats"] = expected["Floats"].astype(np.float32)
for col in parsed_118.columns:
tm.assert_almost_equal(parsed_118[col], expected[col])
with StataReader(datapath("io", "data", "stata", f"{file}.dta")) as rdr:
vl = rdr.variable_labels()
vl_expected = {
"Unicode_Cities_Strl": "Here are some strls with Ünicode chars",
"Longs": "long data",
"Things": "Here are some things",
"Bytes": "byte data",
"Ints": "int data",
"Cities": "Here are some cities",
"Floats": "float data",
}
tm.assert_dict_equal(vl, vl_expected)
assert rdr.data_label == "This is a Ünicode data label"
def test_read_write_dta5(self, temp_file):
original = DataFrame(
[(np.nan, np.nan, np.nan, np.nan, np.nan)],
columns=["float_miss", "double_miss", "byte_miss", "int_miss", "long_miss"],
)
original.index.name = "index"
path = temp_file
original.to_stata(path, convert_dates=None)
written_and_read_again = self.read_dta(path)
expected = original
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
def test_write_dta6(self, datapath, temp_file):
original = self.read_csv(datapath("io", "data", "stata", "stata3.csv"))
original.index.name = "index"
original.index = original.index.astype(np.int32)
original["year"] = original["year"].astype(np.int32)
original["quarter"] = original["quarter"].astype(np.int32)
path = temp_file
original.to_stata(path, convert_dates=None)
written_and_read_again = self.read_dta(path)
tm.assert_frame_equal(
written_and_read_again.set_index("index"),
original,
check_index_type=False,
)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_write_dta10(self, version, temp_file, using_infer_string):
original = DataFrame(
data=[["string", "object", 1, 1.1, np.datetime64("2003-12-25")]],
columns=["string", "object", "integer", "floating", "datetime"],
)
original["object"] = Series(original["object"], dtype=object)
original.index.name = "index"
original.index = original.index.astype(np.int32)
original["integer"] = original["integer"].astype(np.int32)
path = temp_file
original.to_stata(path, convert_dates={"datetime": "tc"}, version=version)
written_and_read_again = self.read_dta(path)
expected = original.copy()
# "tc" convert_dates means we store in ms
expected["datetime"] = expected["datetime"].astype("M8[ms]")
if using_infer_string:
expected["object"] = expected["object"].astype("str")
tm.assert_frame_equal(
written_and_read_again.set_index("index"),
expected,
)
def test_stata_doc_examples(self, temp_file):
path = temp_file
df = DataFrame(
np.random.default_rng(2).standard_normal((10, 2)), columns=list("AB")
)
df.to_stata(path)
def test_write_preserves_original(self, temp_file):
# 9795
df = DataFrame(
np.random.default_rng(2).standard_normal((5, 4)), columns=list("abcd")
)
df.loc[2, "a":"c"] = np.nan
df_copy = df.copy()
path = temp_file
df.to_stata(path, write_index=False)
tm.assert_frame_equal(df, df_copy)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_encoding(self, version, datapath, temp_file):
# GH 4626, proper encoding handling
raw = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))
encoded = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta"))
result = encoded.kreis1849[0]
expected = raw.kreis1849[0]
assert result == expected
assert isinstance(result, str)
path = temp_file
encoded.to_stata(path, write_index=False, version=version)
reread_encoded = read_stata(path)
tm.assert_frame_equal(encoded, reread_encoded)
def test_read_write_dta11(self, temp_file):
original = DataFrame(
[(1, 2, 3, 4)],
columns=[
"good",
"b\u00e4d",
"8number",
"astringwithmorethan32characters______",
],
)
formatted = DataFrame(
[(1, 2, 3, 4)],
columns=["good", "b_d", "_8number", "astringwithmorethan32characters_"],
)
formatted.index.name = "index"
formatted = formatted.astype(np.int32)
path = temp_file
msg = "Not all pandas column names were valid Stata variable names"
with tm.assert_produces_warning(InvalidColumnName, match=msg):
original.to_stata(path, convert_dates=None)
written_and_read_again = self.read_dta(path)
expected = formatted
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_write_dta12(self, version, temp_file):
original = DataFrame(
[(1, 2, 3, 4, 5, 6)],
columns=[
"astringwithmorethan32characters_1",
"astringwithmorethan32characters_2",
"+",
"-",
"short",
"delete",
],
)
formatted = DataFrame(
[(1, 2, 3, 4, 5, 6)],
columns=[
"astringwithmorethan32characters_",
"_0astringwithmorethan32character",
"_",
"_1_",
"_short",
"_delete",
],
)
formatted.index.name = "index"
formatted = formatted.astype(np.int32)
path = temp_file
msg = "Not all pandas column names were valid Stata variable names"
with tm.assert_produces_warning(InvalidColumnName, match=msg):
original.to_stata(path, convert_dates=None, version=version)
# should get a warning for that format.
written_and_read_again = self.read_dta(path)
expected = formatted
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
def test_read_write_dta13(self, temp_file):
s1 = Series(2**9, dtype=np.int16)
s2 = Series(2**17, dtype=np.int32)
s3 = Series(2**33, dtype=np.int64)
original = DataFrame({"int16": s1, "int32": s2, "int64": s3})
original.index.name = "index"
formatted = original
formatted["int64"] = formatted["int64"].astype(np.float64)
path = temp_file
original.to_stata(path)
written_and_read_again = self.read_dta(path)
expected = formatted
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
@pytest.mark.parametrize(
"file", ["stata5_113", "stata5_114", "stata5_115", "stata5_117"]
)
def test_read_write_reread_dta14(
self, file, parsed_114, version, datapath, temp_file
):
file = datapath("io", "data", "stata", f"{file}.dta")
parsed = self.read_dta(file)
parsed.index.name = "index"
tm.assert_frame_equal(parsed_114, parsed)
path = temp_file
parsed_114.to_stata(path, convert_dates={"date_td": "td"}, version=version)
written_and_read_again = self.read_dta(path)
expected = parsed_114.copy()
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
@pytest.mark.parametrize(
"file", ["stata6_113", "stata6_114", "stata6_115", "stata6_117"]
)
def test_read_write_reread_dta15(self, file, datapath):
expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv"))
expected["byte_"] = expected["byte_"].astype(np.int8)
expected["int_"] = expected["int_"].astype(np.int16)
expected["long_"] = expected["long_"].astype(np.int32)
expected["float_"] = expected["float_"].astype(np.float32)
expected["double_"] = expected["double_"].astype(np.float64)
# TODO(GH#55564): directly cast to M8[s]
arr = expected["date_td"].astype("Period[D]")._values.asfreq("s", how="S")
expected["date_td"] = arr.view("M8[s]")
file = datapath("io", "data", "stata", f"{file}.dta")
parsed = self.read_dta(file)
tm.assert_frame_equal(expected, parsed)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_timestamp_and_label(self, version, temp_file):
original = DataFrame([(1,)], columns=["variable"])
time_stamp = datetime(2000, 2, 29, 14, 21)
data_label = "This is a data file."
path = temp_file
original.to_stata(
path, time_stamp=time_stamp, data_label=data_label, version=version
)
with StataReader(path) as reader:
assert reader.time_stamp == "29 Feb 2000 14:21"
assert reader.data_label == data_label
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_invalid_timestamp(self, version, temp_file):
original = DataFrame([(1,)], columns=["variable"])
time_stamp = "01 Jan 2000, 00:00:00"
path = temp_file
msg = "time_stamp should be datetime type"
with pytest.raises(ValueError, match=msg):
original.to_stata(path, time_stamp=time_stamp, version=version)
assert not os.path.isfile(path)
def test_numeric_column_names(self, temp_file):
original = DataFrame(np.reshape(np.arange(25.0), (5, 5)))
original.index.name = "index"
path = temp_file
# should get a warning for that format.
msg = "Not all pandas column names were valid Stata variable names"
with tm.assert_produces_warning(InvalidColumnName, match=msg):
original.to_stata(path)
written_and_read_again = self.read_dta(path)
written_and_read_again = written_and_read_again.set_index("index")
columns = list(written_and_read_again.columns)
convert_col_name = lambda x: int(x[1])
written_and_read_again.columns = map(convert_col_name, columns)
expected = original
tm.assert_frame_equal(expected, written_and_read_again)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_nan_to_missing_value(self, version, temp_file):
s1 = Series(np.arange(4.0), dtype=np.float32)
s2 = Series(np.arange(4.0), dtype=np.float64)
s1[::2] = np.nan
s2[1::2] = np.nan
original = DataFrame({"s1": s1, "s2": s2})
original.index.name = "index"
path = temp_file
original.to_stata(path, version=version)
written_and_read_again = self.read_dta(path)
written_and_read_again = written_and_read_again.set_index("index")
expected = original
tm.assert_frame_equal(written_and_read_again, expected)
def test_no_index(self, temp_file):
columns = ["x", "y"]
original = DataFrame(np.reshape(np.arange(10.0), (5, 2)), columns=columns)
original.index.name = "index_not_written"
path = temp_file
original.to_stata(path, write_index=False)
written_and_read_again = self.read_dta(path)
with pytest.raises(KeyError, match=original.index.name):
written_and_read_again["index_not_written"]
def test_string_no_dates(self, temp_file):
s1 = Series(["a", "A longer string"])
s2 = Series([1.0, 2.0], dtype=np.float64)
original = DataFrame({"s1": s1, "s2": s2})
original.index.name = "index"
path = temp_file
original.to_stata(path)
written_and_read_again = self.read_dta(path)
expected = original
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
def test_large_value_conversion(self, temp_file):
s0 = Series([1, 99], dtype=np.int8)
s1 = Series([1, 127], dtype=np.int8)
s2 = Series([1, 2**15 - 1], dtype=np.int16)
s3 = Series([1, 2**63 - 1], dtype=np.int64)
original = DataFrame({"s0": s0, "s1": s1, "s2": s2, "s3": s3})
original.index.name = "index"
path = temp_file
with tm.assert_produces_warning(PossiblePrecisionLoss, match="from int64 to"):
original.to_stata(path)
written_and_read_again = self.read_dta(path)
modified = original
modified["s1"] = Series(modified["s1"], dtype=np.int16)
modified["s2"] = Series(modified["s2"], dtype=np.int32)
modified["s3"] = Series(modified["s3"], dtype=np.float64)
tm.assert_frame_equal(written_and_read_again.set_index("index"), modified)
def test_dates_invalid_column(self, temp_file):
original = DataFrame([datetime(2006, 11, 19, 23, 13, 20)])
original.index.name = "index"
path = temp_file
msg = "Not all pandas column names were valid Stata variable names"
with tm.assert_produces_warning(InvalidColumnName, match=msg):
original.to_stata(path, convert_dates={0: "tc"})
written_and_read_again = self.read_dta(path)
expected = original.copy()
expected.columns = ["_0"]
expected.index = original.index.astype(np.int32)
expected["_0"] = expected["_0"].astype("M8[ms]")
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
def test_105(self, datapath):
# Data obtained from:
# http://go.worldbank.org/ZXY29PVJ21
dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")
df = read_stata(dpath)
df0 = [[1, 1, 3, -2], [2, 1, 2, -2], [4, 1, 1, -2]]
df0 = DataFrame(df0)
df0.columns = ["clustnum", "pri_schl", "psch_num", "psch_dis"]
df0["clustnum"] = df0["clustnum"].astype(np.int16)
df0["pri_schl"] = df0["pri_schl"].astype(np.int8)
df0["psch_num"] = df0["psch_num"].astype(np.int8)
df0["psch_dis"] = df0["psch_dis"].astype(np.float32)
tm.assert_frame_equal(df.head(3), df0)
def test_value_labels_old_format(self, datapath):
# GH 19417
#
# Test that value_labels() returns an empty dict if the file format
# predates supporting value labels.
dpath = datapath("io", "data", "stata", "S4_EDUC1.dta")
with StataReader(dpath) as reader:
assert reader.value_labels() == {}
def test_date_export_formats(self, temp_file):
columns = ["tc", "td", "tw", "tm", "tq", "th", "ty"]
conversions = {c: c for c in columns}
data = [datetime(2006, 11, 20, 23, 13, 20)] * len(columns)
original = DataFrame([data], columns=columns)
original.index.name = "index"
expected_values = [
datetime(2006, 11, 20, 23, 13, 20), # Time
datetime(2006, 11, 20), # Day
datetime(2006, 11, 19), # Week
datetime(2006, 11, 1), # Month
datetime(2006, 10, 1), # Quarter year
datetime(2006, 7, 1), # Half year
datetime(2006, 1, 1),
] # Year
expected = DataFrame(
[expected_values],
index=pd.Index([0], dtype=np.int32, name="index"),
columns=columns,
dtype="M8[s]",
)
expected["tc"] = expected["tc"].astype("M8[ms]")
path = temp_file
original.to_stata(path, convert_dates=conversions)
written_and_read_again = self.read_dta(path)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
def test_write_missing_strings(self, temp_file):
original = DataFrame([["1"], [None]], columns=["foo"])
expected = DataFrame(
[["1"], [""]],
index=pd.RangeIndex(2, name="index"),
columns=["foo"],
)
path = temp_file
original.to_stata(path)
written_and_read_again = self.read_dta(path)
tm.assert_frame_equal(written_and_read_again.set_index("index"), expected)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
@pytest.mark.parametrize("byteorder", [">", "<"])
def test_bool_uint(self, byteorder, version, temp_file):
s0 = Series([0, 1, True], dtype=np.bool_)
s1 = Series([0, 1, 100], dtype=np.uint8)
s2 = Series([0, 1, 255], dtype=np.uint8)
s3 = Series([0, 1, 2**15 - 100], dtype=np.uint16)
s4 = Series([0, 1, 2**16 - 1], dtype=np.uint16)
s5 = Series([0, 1, 2**31 - 100], dtype=np.uint32)
s6 = Series([0, 1, 2**32 - 1], dtype=np.uint32)
original = DataFrame(
{"s0": s0, "s1": s1, "s2": s2, "s3": s3, "s4": s4, "s5": s5, "s6": s6}
)
original.index.name = "index"
path = temp_file
original.to_stata(path, byteorder=byteorder, version=version)
written_and_read_again = self.read_dta(path)
written_and_read_again = written_and_read_again.set_index("index")
expected = original
expected_types = (
np.int8,
np.int8,
np.int16,
np.int16,
np.int32,
np.int32,
np.float64,
)
for c, t in zip(expected.columns, expected_types):
expected[c] = expected[c].astype(t)
tm.assert_frame_equal(written_and_read_again, expected)
def test_variable_labels(self, datapath):
with StataReader(datapath("io", "data", "stata", "stata7_115.dta")) as rdr:
sr_115 = rdr.variable_labels()
with StataReader(datapath("io", "data", "stata", "stata7_117.dta")) as rdr:
sr_117 = rdr.variable_labels()
keys = ("var1", "var2", "var3")
labels = ("label1", "label2", "label3")
for k, v in sr_115.items():
assert k in sr_117
assert v == sr_117[k]
assert k in keys
assert v in labels
def test_minimal_size_col(self, temp_file):
str_lens = (1, 100, 244)
s = {}
for str_len in str_lens:
s["s" + str(str_len)] = Series(
["a" * str_len, "b" * str_len, "c" * str_len]
)
original = DataFrame(s)
path = temp_file
original.to_stata(path, write_index=False)
with StataReader(path) as sr:
sr._ensure_open() # The `_*list` variables are initialized here
for variable, fmt, typ in zip(sr._varlist, sr._fmtlist, sr._typlist):
assert int(variable[1:]) == int(fmt[1:-1])
assert int(variable[1:]) == typ
def test_excessively_long_string(self, temp_file):
str_lens = (1, 244, 500)
s = {}
for str_len in str_lens:
s["s" + str(str_len)] = Series(
["a" * str_len, "b" * str_len, "c" * str_len]
)
original = DataFrame(s)
msg = (
r"Fixed width strings in Stata \.dta files are limited to 244 "
r"\(or fewer\)\ncharacters\. Column 's500' does not satisfy "
r"this restriction\. Use the\n'version=117' parameter to write "
r"the newer \(Stata 13 and later\) format\."
)
with pytest.raises(ValueError, match=msg):
path = temp_file
original.to_stata(path)
def test_missing_value_generator(self, temp_file):
types = ("b", "h", "l")
df = DataFrame([[0.0]], columns=["float_"])
path = temp_file
df.to_stata(path)
with StataReader(path) as rdr:
valid_range = rdr.VALID_RANGE
expected_values = ["." + chr(97 + i) for i in range(26)]
expected_values.insert(0, ".")
for t in types:
offset = valid_range[t][1]
for i in range(27):
val = StataMissingValue(offset + 1 + i)
assert val.string == expected_values[i]
# Test extremes for floats
val = StataMissingValue(struct.unpack("<f", b"\x00\x00\x00\x7f")[0])
assert val.string == "."
val = StataMissingValue(struct.unpack("<f", b"\x00\xd0\x00\x7f")[0])
assert val.string == ".z"
# Test extremes for floats
val = StataMissingValue(
struct.unpack("<d", b"\x00\x00\x00\x00\x00\x00\xe0\x7f")[0]
)
assert val.string == "."
val = StataMissingValue(
struct.unpack("<d", b"\x00\x00\x00\x00\x00\x1a\xe0\x7f")[0]
)
assert val.string == ".z"
@pytest.mark.parametrize("version", [113, 115, 117])
def test_missing_value_conversion(self, version, datapath):
columns = ["int8_", "int16_", "int32_", "float32_", "float64_"]
smv = StataMissingValue(101)
keys = sorted(smv.MISSING_VALUES.keys())
data = []
for i in range(27):
row = [StataMissingValue(keys[i + (j * 27)]) for j in range(5)]
data.append(row)
expected = DataFrame(data, columns=columns)
parsed = read_stata(
datapath("io", "data", "stata", f"stata8_{version}.dta"),
convert_missing=True,
)
tm.assert_frame_equal(parsed, expected)
@pytest.mark.parametrize("version", [104, 105, 108, 110, 111])
def test_missing_value_conversion_compat(self, version, datapath):
columns = ["int8_", "int16_", "int32_", "float32_", "float64_"]
smv = StataMissingValue(101)
keys = sorted(smv.MISSING_VALUES.keys())
data = []
row = [StataMissingValue(keys[j * 27]) for j in range(5)]
data.append(row)
expected = DataFrame(data, columns=columns)
parsed = read_stata(
datapath("io", "data", "stata", f"stata8_{version}.dta"),
convert_missing=True,
)
tm.assert_frame_equal(parsed, expected)
# The byte type was not supported prior to the 104 format
@pytest.mark.parametrize("version", [102, 103])
def test_missing_value_conversion_compat_nobyte(self, version, datapath):
columns = ["int8_", "int16_", "int32_", "float32_", "float64_"]
smv = StataMissingValue(101)
keys = sorted(smv.MISSING_VALUES.keys())
data = []
row = [StataMissingValue(keys[j * 27]) for j in [1, 1, 2, 3, 4]]
data.append(row)
expected = DataFrame(data, columns=columns)
parsed = read_stata(
datapath("io", "data", "stata", f"stata8_{version}.dta"),
convert_missing=True,
)
tm.assert_frame_equal(parsed, expected)
def test_big_dates(self, datapath, temp_file):
yr = [1960, 2000, 9999, 100, 2262, 1677]
mo = [1, 1, 12, 1, 4, 9]
dd = [1, 1, 31, 1, 22, 23]
hr = [0, 0, 23, 0, 0, 0]
mm = [0, 0, 59, 0, 0, 0]
ss = [0, 0, 59, 0, 0, 0]
expected = []
for year, month, day, hour, minute, second in zip(yr, mo, dd, hr, mm, ss):
row = []
for j in range(7):
if j == 0:
row.append(datetime(year, month, day, hour, minute, second))
elif j == 6:
row.append(datetime(year, 1, 1))
else:
row.append(datetime(year, month, day))
expected.append(row)
expected.append([pd.NaT] * 7)
columns = [
"date_tc",
"date_td",
"date_tw",
"date_tm",
"date_tq",
"date_th",