Python|熊猫 Series.to_numpy()
Pandas Series.to_numpy()函数用于返回一个 NumPy ndarray,表示给定系列或索引中的值。
这个函数将解释我们如何将 pandas Series转换为 numpy Array 。虽然它非常简单,但这种技术背后的概念却非常独特。因为我们知道 Series 在输出中有索引。而在 numpy 数组中,我们只有 numpy 数组中的元素。
Syntax: Series.to_numpy()
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.
要获取 csv 文件的链接,请单击 nba.csv
代码#1:
使用方法Series.to_numpy()
将 Series 更改为numpy 数组。永远记住,在处理大量数据时,您应该首先清理数据以获得高精度。尽管在此代码中,我们使用.head()
方法使用Weight列的前五个值。
# importing pandas
import pandas as pd
# reading the csv
data = pd.read_csv("nba.csv")
data.dropna(inplace = True)
# creating series form weight column
gfg = pd.Series(data['Weight'].head())
# using to_numpy() function
print(type(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 series form weight column
gfg = pd.Series(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 series form weight column
gfg = pd.Series(data['Weight'].head())
# using to_numpy()
print(type(gfg.to_numpy()))
输出 :