@@ -162,37 +162,28 @@ def _to_numpy(data: Any) -> np.ndarray:
162
162
"date64[ms][pyarrow]" : np .datetime64 ,
163
163
}
164
164
165
+ # The expected numpy dtype for the result numpy array, but can be None.
166
+ dtype = dtypes .get (str (getattr (data , "dtype" , None )))
167
+
168
+ # Workarounds for pandas < 2.2. Following SPEC 0, pandas 2.1 should be dropped in
169
+ # 2025 Q3, so it's likely we can remove the workaround in PyGMT v0.17.0.
170
+ #
165
171
# pandas numeric dtypes were converted to np.object_ dtype prior pandas 2.2, and are
166
172
# converted to suitable NumPy dtypes since pandas 2.2. Refer to the following link
167
173
# for details: https://pandas.pydata.org/docs/whatsnew/v2.2.0.html#to-numpy-for-numpy-nullable-and-arrow-types-converts-to-suitable-numpy-dtype
168
- # Here are the workarounds for pandas < 2.2.
169
- # Following SPEC 0, pandas 2.1 should be dropped in 2025 Q3, so it's likely we can
170
- # remove the workaround in PyGMT v0.17.0.
171
- if Version (pd .__version__ ) < Version ("2.2" ):
172
- # Specify mapping from pandas nullable dtypes to suitable NumPy dtypes
173
- dtypes .update (
174
- {
175
- "Int8" : np .int8 ,
176
- "Int16" : np .int16 ,
177
- "Int32" : np .int32 ,
178
- "Int64" : np .int64 ,
179
- "UInt8" : np .uint8 ,
180
- "UInt16" : np .uint16 ,
181
- "UInt32" : np .uint32 ,
182
- "UInt64" : np .uint64 ,
183
- "Float32" : np .float32 ,
184
- "Float64" : np .float64 ,
185
- }
186
- )
187
- # For pandas.Index/pandas.Series, pandas/PyArrow integer dtypes with missing
188
- # values should be cast to NumPy float dtypes and NaN is used as missing value
189
- # indicator.
190
- if getattr (data , "hasnans" , False ): # pandas.Index/pandas.Series has 'hasnans'
191
- dtype = np .float64 if data .dtype .kind in "iu" else data .dtype .numpy_dtype
192
- data = data .to_numpy (na_value = np .nan ).astype (dtype = dtype )
193
-
194
- vec_dtype = str (getattr (data , "dtype" , "" ))
195
- array = np .ascontiguousarray (data , dtype = dtypes .get (vec_dtype ))
174
+ if (
175
+ Version (pd .__version__ ) < Version ("2.2" )
176
+ and hasattr (data , "dtype" )
177
+ and hasattr (data .dtype , "numpy_dtype" )
178
+ ): # pandas.Series/pandas.Index with pandas nullable dtypes.
179
+ dtype = data .dtype .numpy_dtype
180
+ if data .hasnans :
181
+ if data .dtype .kind in "iu" :
182
+ # Integers with missing values are converted to float64
183
+ dtype = np .float64
184
+ data = data .to_numpy (na_value = np .nan )
185
+
186
+ array = np .ascontiguousarray (data , dtype = dtype )
196
187
return array
197
188
198
189
0 commit comments