Pandas Dataframe.to_numpy() - 将数据帧转换为 Numpy 数组
Pandas DataFrame 是具有标记轴(行和列)的二维大小可变、可能异构的表格数据结构。可以借助Dataframe.to_numpy()方法将此数据结构转换为 NumPy ndarray。
Syntax: Dataframe.to_numpy(dtype = None, copy = False)
Parameters:
dtype: Data type which we are passing like str.
copy: [bool, default False] Ensures that the returned value is a not a view on another array.
Returns:
numpy.ndarray
要获取 csv 文件的链接,请单击 nba.csv
示例 1:使用DataFrame.to_numpy()
方法将 DataFrame 更改为 numpy 数组。永远记住,在处理大量数据时,您应该首先清理数据以获得高精度。尽管在此代码中,我们使用.head()
方法使用 Weight 列的前五个值。
# importing pandas
import pandas as pd
# reading the csv
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
# using to_numpy() function
print(gfg.to_numpy())
输出:
[[180.]
[235.]
[185.]
[235.]
[238.]]
示例 2:在此代码中,我们只是在同一代码中提供参数。所以我们在这里提供dtype。
# importing pandas
import pandas as pd
# read csv file
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
# providing dtype
print(gfg.to_numpy(dtype ='float32'))
输出:
[[180.]
[235.]
[185.]
[235.]
[238.]]
示例 3:转换后验证数组的类型。
# importing pandas
import pandas as pd
# reading csv
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
# creating DataFrame form weight column
gfg = pd.DataFrame(data['Weight'].head())
# using to_numpy()
print(type(gfg.to_numpy()))
输出: