将pandas数据框转换为numpy数组-首选哪种方法? [英] Convert pandas dataframe to numpy array - which approach to prefer?
问题描述
我需要将大数据帧转换为numpy数组. 仅保留数值和类型. 我知道有充分的记录方法.
I need to convert a large dataframe to a numpy array. Preserving only numerical values and types. I know there are well documented ways to do so.
那么,哪一个更受欢迎?
So, which one is to prefer?
df.values
df._as_matrix()
pd.to_numeric(df)
... others ...
决定因素:
-
效率
efficiency
在nan,np.nans和其他可能的意外值上安全运行
safely operating on nan,np.nans, and other possible unexpected values
数值稳定
推荐答案
您提到的功能有不同的用途.
The functions you mention serve different purposes.
-
pd.to_numeric
:如果当前数据不是以数字形式或存储,则可以使用它来转换数据框中的类型 通过downcast='float'
强制转换为最佳类型downcast='integer'
.
pd.to_numeric
: Use this to convert types in your dataframe if your data is not currently stored in numeric form or if you wish to cast as an optimal type viadowncast='float'
ordowncast='integer'
.
pd.DataFrame.to_numpy()
(v0.24 +)或
pd.DataFrame.to_numpy()
(v0.24+) or pd.DataFrame.values
: Use this to retrieve numpy
array representation of your dataframe.
pd.DataFrame.as_matrix
:请勿使用此功能.仅包括它是为了向后兼容.
pd.DataFrame.as_matrix
: Do not use this. It is included only for backwards compatibility.
这篇关于将pandas数据框转换为numpy数组-首选哪种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!