1
1
# coding=utf-8
2
2
# pylint: disable-msg=E1101,W0612
3
3
4
- import sys
4
+ import pytest
5
+
5
6
from datetime import datetime
7
+
8
+ import sys
6
9
import string
10
+ import warnings
7
11
8
12
from numpy import nan
9
13
import numpy as np
12
16
13
17
from pandas .compat import lrange , range , u
14
18
from pandas import compat
15
- from pandas .util .testing import assert_series_equal
16
19
import pandas .util .testing as tm
17
20
18
21
from .common import TestData
19
22
20
23
21
- class TestSeriesDtypes (TestData , tm . TestCase ):
24
+ class TestSeriesDtypes (TestData ):
22
25
23
- def test_astype (self ):
26
+ @pytest .mark .parametrize ("dtype" , ["float32" , "float64" ,
27
+ "int64" , "int32" ])
28
+ def test_astype (self , dtype ):
24
29
s = Series (np .random .randn (5 ), name = 'foo' )
30
+ as_typed = s .astype (dtype )
25
31
26
- for dtype in ['float32' , 'float64' , 'int64' , 'int32' ]:
27
- astyped = s .astype (dtype )
28
- self .assertEqual (astyped .dtype , dtype )
29
- self .assertEqual (astyped .name , s .name )
32
+ assert as_typed .dtype == dtype
33
+ assert as_typed .name == s .name
30
34
31
35
def test_dtype (self ):
32
36
33
- self .assertEqual (self .ts .dtype , np .dtype ('float64' ))
34
- self .assertEqual (self .ts .dtypes , np .dtype ('float64' ))
35
- self .assertEqual (self .ts .ftype , 'float64:dense' )
36
- self .assertEqual (self .ts .ftypes , 'float64:dense' )
37
- assert_series_equal (self .ts .get_dtype_counts (), Series (1 , ['float64' ]))
38
- assert_series_equal (self .ts .get_ftype_counts (), Series (
39
- 1 , ['float64:dense' ]))
40
-
41
- def test_astype_cast_nan_inf_int (self ):
42
- # GH14265, check nan and inf raise error when converting to int
43
- types = [np .int32 , np .int64 ]
44
- values = [np .nan , np .inf ]
37
+ assert self .ts .dtype == np .dtype ('float64' )
38
+ assert self .ts .dtypes == np .dtype ('float64' )
39
+ assert self .ts .ftype == 'float64:dense'
40
+ assert self .ts .ftypes == 'float64:dense'
41
+ tm .assert_series_equal (self .ts .get_dtype_counts (),
42
+ Series (1 , ['float64' ]))
43
+ tm .assert_series_equal (self .ts .get_ftype_counts (),
44
+ Series (1 , ['float64:dense' ]))
45
+
46
+ @pytest .mark .parametrize ("value" , [np .nan , np .inf ])
47
+ @pytest .mark .parametrize ("dtype" , [np .int32 , np .int64 ])
48
+ def test_astype_cast_nan_inf_int (self , dtype , value ):
49
+ # gh-14265: check NaN and inf raise error when converting to int
45
50
msg = 'Cannot convert non-finite values \\ (NA or inf\\ ) to integer'
51
+ s = Series ([value ])
46
52
47
- for this_type in types :
48
- for this_val in values :
49
- s = Series ([this_val ])
50
- with self .assertRaisesRegexp (ValueError , msg ):
51
- s .astype (this_type )
53
+ with tm .assertRaisesRegexp (ValueError , msg ):
54
+ s .astype (dtype )
52
55
53
- def test_astype_cast_object_int (self ):
56
+ @pytest .mark .parametrize ("dtype" , [int , np .int8 , np .int64 ])
57
+ def test_astype_cast_object_int_fail (self , dtype ):
54
58
arr = Series (["car" , "house" , "tree" , "1" ])
59
+ with pytest .raises (ValueError ):
60
+ arr .astype (dtype )
55
61
56
- self .assertRaises (ValueError , arr .astype , int )
57
- self .assertRaises (ValueError , arr .astype , np .int64 )
58
- self .assertRaises (ValueError , arr .astype , np .int8 )
59
-
62
+ def test_astype_cast_object_int (self ):
60
63
arr = Series (['1' , '2' , '3' , '4' ], dtype = object )
61
64
result = arr .astype (int )
62
- self .assert_series_equal (result , Series (np .arange (1 , 5 )))
65
+
66
+ tm .assert_series_equal (result , Series (np .arange (1 , 5 )))
63
67
64
68
def test_astype_datetimes (self ):
65
69
import pandas ._libs .tslib as tslib
66
-
67
70
s = Series (tslib .iNaT , dtype = 'M8[ns]' , index = lrange (5 ))
71
+
68
72
s = s .astype ('O' )
69
- self . assertEqual ( s .dtype , np .object_ )
73
+ assert s .dtype == np .object_
70
74
71
75
s = Series ([datetime (2001 , 1 , 2 , 0 , 0 )])
76
+
72
77
s = s .astype ('O' )
73
- self . assertEqual ( s .dtype , np .object_ )
78
+ assert s .dtype == np .object_
74
79
75
80
s = Series ([datetime (2001 , 1 , 2 , 0 , 0 ) for i in range (3 )])
81
+
76
82
s [1 ] = np .nan
77
- self .assertEqual (s .dtype , 'M8[ns]' )
78
- s = s .astype ('O' )
79
- self .assertEqual (s .dtype , np .object_ )
83
+ assert s .dtype == 'M8[ns]'
80
84
81
- def test_astype_str (self ):
82
- # GH4405
83
- digits = string .digits
84
- s1 = Series ([digits * 10 , tm .rands (63 ), tm .rands (64 ), tm .rands (1000 )])
85
- s2 = Series ([digits * 10 , tm .rands (63 ), tm .rands (64 ), nan , 1.0 ])
86
- types = (compat .text_type , np .str_ )
87
- for typ in types :
88
- for s in (s1 , s2 ):
89
- res = s .astype (typ )
90
- expec = s .map (compat .text_type )
91
- assert_series_equal (res , expec )
92
-
93
- # GH9757
94
- # Test str and unicode on python 2.x and just str on python 3.x
95
- for tt in set ([str , compat .text_type ]):
96
- ts = Series ([Timestamp ('2010-01-04 00:00:00' )])
97
- s = ts .astype (tt )
98
- expected = Series ([tt ('2010-01-04' )])
99
- assert_series_equal (s , expected )
100
-
101
- ts = Series ([Timestamp ('2010-01-04 00:00:00' , tz = 'US/Eastern' )])
102
- s = ts .astype (tt )
103
- expected = Series ([tt ('2010-01-04 00:00:00-05:00' )])
104
- assert_series_equal (s , expected )
105
-
106
- td = Series ([Timedelta (1 , unit = 'd' )])
107
- s = td .astype (tt )
108
- expected = Series ([tt ('1 days 00:00:00.000000000' )])
109
- assert_series_equal (s , expected )
85
+ s = s .astype ('O' )
86
+ assert s .dtype == np .object_
87
+
88
+ @pytest .mark .parametrize ("dtype" , [compat .text_type , np .str_ ])
89
+ @pytest .mark .parametrize ("series" , [Series ([string .digits * 10 ,
90
+ tm .rands (63 ),
91
+ tm .rands (64 ),
92
+ tm .rands (1000 )]),
93
+ Series ([string .digits * 10 ,
94
+ tm .rands (63 ),
95
+ tm .rands (64 ), nan , 1.0 ])])
96
+ def test_astype_str_map (self , dtype , series ):
97
+ # see gh-4405
98
+ result = series .astype (dtype )
99
+ expected = series .map (compat .text_type )
100
+ tm .assert_series_equal (result , expected )
101
+
102
+ @pytest .mark .parametrize ("dtype" , [str , compat .text_type ])
103
+ def test_astype_str_cast (self , dtype ):
104
+ # see gh-9757: test str and unicode on python 2.x
105
+ # and just str on python 3.x
106
+ ts = Series ([Timestamp ('2010-01-04 00:00:00' )])
107
+ s = ts .astype (dtype )
108
+
109
+ expected = Series ([dtype ('2010-01-04' )])
110
+ tm .assert_series_equal (s , expected )
111
+
112
+ ts = Series ([Timestamp ('2010-01-04 00:00:00' , tz = 'US/Eastern' )])
113
+ s = ts .astype (dtype )
114
+
115
+ expected = Series ([dtype ('2010-01-04 00:00:00-05:00' )])
116
+ tm .assert_series_equal (s , expected )
117
+
118
+ td = Series ([Timedelta (1 , unit = 'd' )])
119
+ s = td .astype (dtype )
120
+
121
+ expected = Series ([dtype ('1 days 00:00:00.000000000' )])
122
+ tm .assert_series_equal (s , expected )
110
123
111
124
def test_astype_unicode (self ):
112
-
113
- # GH7758
114
- # a bit of magic is required to set default encoding encoding to utf-8
125
+ # see gh-7758: A bit of magic is required to set
126
+ # default encoding to utf-8
115
127
digits = string .digits
116
128
test_series = [
117
129
Series ([digits * 10 , tm .rands (63 ), tm .rands (64 ), tm .rands (1000 )]),
118
130
Series ([u ('データーサイエンス、お前はもう死んでいる' )]),
119
-
120
131
]
121
132
122
133
former_encoding = None
134
+
123
135
if not compat .PY3 :
124
- # in python we can force the default encoding for this test
136
+ # In Python, we can force the default encoding for this test
125
137
former_encoding = sys .getdefaultencoding ()
126
138
reload (sys ) # noqa
139
+
127
140
sys .setdefaultencoding ("utf-8" )
128
141
if sys .getdefaultencoding () == "utf-8" :
129
142
test_series .append (Series ([u ('野菜食べないとやばい' )
130
143
.encode ("utf-8" )]))
144
+
131
145
for s in test_series :
132
146
res = s .astype ("unicode" )
133
147
expec = s .map (compat .text_type )
134
- assert_series_equal (res , expec )
135
- # restore the former encoding
148
+ tm .assert_series_equal (res , expec )
149
+
150
+ # Restore the former encoding
136
151
if former_encoding is not None and former_encoding != "utf-8" :
137
152
reload (sys ) # noqa
138
153
sys .setdefaultencoding (former_encoding )
139
154
140
155
def test_astype_dict (self ):
141
- # GH7271
156
+ # see gh-7271
142
157
s = Series (range (0 , 10 , 2 ), name = 'abc' )
143
158
144
159
result = s .astype ({'abc' : str })
145
160
expected = Series (['0' , '2' , '4' , '6' , '8' ], name = 'abc' )
146
- assert_series_equal (result , expected )
161
+ tm . assert_series_equal (result , expected )
147
162
148
163
result = s .astype ({'abc' : 'float64' })
149
164
expected = Series ([0.0 , 2.0 , 4.0 , 6.0 , 8.0 ], dtype = 'float64' ,
150
165
name = 'abc' )
151
- assert_series_equal (result , expected )
166
+ tm . assert_series_equal (result , expected )
152
167
153
- self . assertRaises (KeyError , s . astype , { 'abc' : str , 'def' : str })
154
- self . assertRaises ( KeyError , s .astype , { 0 : str })
168
+ with pytest . raises (KeyError ):
169
+ s .astype ({ 'abc' : str , 'def' : str })
155
170
156
- def test_astype_generic_timestamp (self ):
171
+ with pytest .raises (KeyError ):
172
+ s .astype ({0 : str })
173
+
174
+ def test_astype_generic_timestamp_deprecated (self ):
157
175
# see gh-15524
158
176
data = [1 ]
159
177
160
- s = Series (data )
161
- dtype = np .datetime64
162
- result = s .astype (dtype )
163
- expected = Series (data , dtype = dtype )
164
- assert_series_equal (result , expected )
165
-
166
- s = Series (data )
167
- dtype = np .timedelta64
168
- result = s .astype (dtype )
169
- expected = Series (data , dtype = dtype )
170
- assert_series_equal (result , expected )
178
+ with tm .assert_produces_warning (FutureWarning ):
179
+ s = Series (data )
180
+ dtype = np .datetime64
181
+ result = s .astype (dtype )
182
+ expected = Series (data , dtype = dtype )
183
+ tm .assert_series_equal (result , expected )
171
184
172
- def test_astype_empty_constructor_equality (self ):
185
+ with tm .assert_produces_warning (FutureWarning ):
186
+ s = Series (data )
187
+ dtype = np .timedelta64
188
+ result = s .astype (dtype )
189
+ expected = Series (data , dtype = dtype )
190
+ tm .assert_series_equal (result , expected )
191
+
192
+ @pytest .mark .parametrize ("dtype" , np .typecodes ['All' ])
193
+ def test_astype_empty_constructor_equality (self , dtype ):
173
194
# see gh-15524
174
195
175
- for dtype in np .typecodes ['All' ]:
176
- if dtype not in ('S' , 'V' ): # poor support (if any) currently
177
- init_empty = Series ([], dtype = dtype )
178
- astype_empty = Series ([]).astype (dtype )
179
-
180
- try :
181
- assert_series_equal (init_empty , astype_empty )
182
- except AssertionError as e :
183
- name = np .dtype (dtype ).name
184
- msg = "{dtype} failed: " .format (dtype = name ) + str (e )
196
+ if dtype not in ('S' , 'V' ): # poor support (if any) currently
197
+ with warnings .catch_warnings (record = True ):
198
+ # Generic timestamp dtypes ('M' and 'm') are deprecated,
199
+ # but we test that already in series/test_constructors.py
185
200
186
- raise AssertionError (msg )
201
+ init_empty = Series ([], dtype = dtype )
202
+ as_type_empty = Series ([]).astype (dtype )
203
+ tm .assert_series_equal (init_empty , as_type_empty )
187
204
188
- def test_complexx (self ):
189
- # GH4819
190
- # complex access for ndarray compat
205
+ def test_complex (self ):
206
+ # see gh-4819: complex access for ndarray compat
191
207
a = np .arange (5 , dtype = np .float64 )
192
208
b = Series (a + 4j * a )
209
+
193
210
tm .assert_numpy_array_equal (a , b .real )
194
211
tm .assert_numpy_array_equal (4 * a , b .imag )
195
212
@@ -198,23 +215,22 @@ def test_complexx(self):
198
215
tm .assert_numpy_array_equal (4 * a , b .imag )
199
216
200
217
def test_arg_for_errors_in_astype (self ):
201
- # issue #14878
202
-
203
- sr = Series ([1 , 2 , 3 ])
218
+ # see gh-14878
219
+ s = Series ([1 , 2 , 3 ])
204
220
205
- with self . assertRaises (ValueError ):
206
- sr .astype (np .float64 , errors = False )
221
+ with pytest . raises (ValueError ):
222
+ s .astype (np .float64 , errors = False )
207
223
208
224
with tm .assert_produces_warning (FutureWarning ):
209
- sr .astype (np .int8 , raise_on_error = True )
225
+ s .astype (np .int8 , raise_on_error = True )
210
226
211
- sr .astype (np .int8 , errors = 'raise' )
227
+ s .astype (np .int8 , errors = 'raise' )
212
228
213
229
def test_intercept_astype_object (self ):
214
230
series = Series (date_range ('1/1/2000' , periods = 10 ))
215
231
216
- # this test no longer makes sense as series is by default already
217
- # M8[ns]
232
+ # This test no longer makes sense, as
233
+ # Series is by default already M8[ns].
218
234
expected = series .astype ('object' )
219
235
220
236
df = DataFrame ({'a' : series ,
@@ -224,9 +240,9 @@ def test_intercept_astype_object(self):
224
240
tm .assert_series_equal (df .dtypes , exp_dtypes )
225
241
226
242
result = df .values .squeeze ()
227
- self . assertTrue (( result [:, 0 ] == expected .values ).all () )
243
+ assert ( result [:, 0 ] == expected .values ).all ()
228
244
229
245
df = DataFrame ({'a' : series , 'b' : ['foo' ] * len (series )})
230
246
231
247
result = df .values .squeeze ()
232
- self . assertTrue (( result [:, 0 ] == expected .values ).all () )
248
+ assert ( result [:, 0 ] == expected .values ).all ()
0 commit comments