为何pandas推荐使用to_numpy()而非DataFrame.values?详细解析
DataFrame.to_numpy() is Preferred Over DataFrame.values Great question! Let's dive into the key reasons pandas recommends to_numpy() over the older .values attribute, and help you decide if updating your code is worth the effort.
1. Consistent Behavior Across Data Types
One of the biggest pain points with .values is its inconsistent handling of mixed or specialized data types. For example:
- If your DataFrame contains a mix of integers and strings,
.valueswill return anobject-dtype array, which can be slow and hard to work with. Whileto_numpy()does the same by default, it lets you explicitly specify adtypeto enforce consistency (e.g.,df.to_numpy(dtype='str')to cast everything to strings). - For pandas' extension dtypes like timezone-aware datetimes (
DatetimeTZDtype) or nullable integers (Int64),.valuesoften falls short. Timezone-aware dates, for instance, get converted to an array ofTimestampobjects (stored asobjectdtype) instead of a native numpy datetime64 array with timezone info.to_numpy()preserves this context, returning a properly typeddatetime64[ns, tz]array that plays nicely with numpy operations.
2. Explicit Control Over Copies and Dtypes
to_numpy() gives you two powerful parameters that .values lacks:
dtype: As mentioned, you can force the output array to a specific data type, avoiding unexpected implicit conversions.copy: You can choose whether to return a copy of the data (copy=True) or a view of the underlying data (copy=False, default when possible). With.values, it's unclear whether you're getting a view or a copy—this can lead to bugs where modifying the array accidentally changes the original DataFrame, or vice versa.to_numpy()makes this behavior explicit.
3. Clearer Code Intent
Let's be honest: .values is a bit ambiguous. Does it return values as a list? A numpy array? For someone reading your code (including future you), df.to_numpy() leaves no room for confusion—it immediately signals that you're converting the DataFrame to a numpy array. This improves code readability and maintainability, especially in larger codebases.
4. Future-Proofing Your Code
While .values isn't deprecated (yet), pandas has clearly stated that to_numpy() is the preferred method for converting DataFrames to numpy arrays. As pandas continues to evolve, .values might receive less maintenance, or even be phased out in future versions. Switching now ensures your code stays compatible with upcoming releases.
Should You Replace All .values Calls?
If your current code works reliably and doesn't deal with tricky data types (like extension dtypes or mixed types), you might not need to rush into replacing every instance. However, if:
- You've run into bugs related to unexpected dtype conversions or view/copy behavior
- Your code uses pandas extension dtypes
- You want to improve code readability or future-proof your project
Then it's absolutely worth making the switch. Most IDEs support bulk find-and-replace (just target .values on DataFrames—note that Series.values is still acceptable, though Series.to_numpy() is also preferred), so updating hundreds of lines shouldn't take too long.
内容的提问来源于stack exchange,提问作者mathguy

