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