python中series是什么意思,python数据类型中series与array的区别

在Python数据处理中,Series是Pandas的基本数据结构之一。当尝试用StandardScaler标准化一维数组时,需先通过reshape转换为二维数组。本文解释了如何使用reshape和shape函数来理解和操作数据的维度,以及Series与1维数组在数据类型和结构上的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在python处理数据时,数据标准化函数StandardScaler进行标准化数据框的某一列数据时,直接选择数据框的某列进行标准化报错:

from sklearn.preprocessing import StandardScaler

StandardScaler().fit_transform(data['Amount'])

f9d9110c8db9c1c1fab13cfbec642e4c.png

报错提醒显示,函数需要的是二维数组,但是命令输入的是一维数组,如果你的数据是一个特征(n*1),那么使用reshape(-1,1)重塑结构,如果数据是一个样本(1*n),那么使用reshape(1,-1)重塑结构。

果然用reshape重塑后顺利:

from sklearn.preprocessing import StandardScaler

print(data['Amount'].head(5))

StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))[0:5]

a19b27997c7c5ad98526440f0738d24e.png

是怎么个回事?

首先查看一下数据类型:

从数据框中直接选出来的某列:

print('数据框series数据类型','\n',type(data['Amount']),

'\n',

'series的结构','\n',data['Amount'].shape)

print('查看series前几个数据','\n',data['Amount'].head(6))

print('\n')

d16f5800246fe883f45a7e57e59b46e9.png

数据类型是series,Series和DataFrame是Pandas的基本数据结构,直接从数据库中选择一列数据,类型是series(选择多列时数据类型是DataFrame)。

从数据框中选择某列取values:

print('1维数组数据类型','\n',type(data['Amount'].values),

'\n',

'为什么说上面是1维数组?,请看其结构:','\n',data['Amount'].values.shape)

print('查看1维数组前几个数据',data['Amount'].values[0:6]) #无法用head()

981077e15cc04c583fe3fce21afd614d.png

数据类型是数组,且是1维的。

而array是Numpy的数据结构。

一维数组转变为二维数组:

#再看reshape处理的

print('2维数组数据类型','\n',type(data['Amount'].values.reshape(-1,1)),

'\n',

'为什么说上面是2维数组?,请看其结构:','\n',

data['Amount'].values.reshape(-1,1).shape)

print('查看2维数组前几个数据',data['Amount'].values.reshape(-1,1)[0:6]) #无法用head()

1216fff3496c34f39f565de6274fa22c.png

python中的shape与reshape函数:

二者是numpy中的函数,功能都是对于数组的形状进行操作。

shape函数可以了解数组的结构;

reshape函数可以对数组结构进行改变。

reshape常见用法:

依次生成n个自然数,并以a行b列的数组形式显示:

np.arange(10).reshape(2,5)

array([[0, 1, 2, 3, 4],

[5, 6, 7, 8, 9]])

np.arange(1,21,2).reshape(2,5)

array([[ 1, 3, 5, 7, 9],

[11, 13, 15, 17, 19]])

reshape函数中的参数需要满足乘积等于数组中数据总数。

reshape(m,-1)或reshape(-1,n)

必须是矩阵格式或数组格式,才能使用,表示将其结构重组,以m行d列或d行n列的形式表示。

这个数d是计算出来的,也就是参数-1的作用。

d=数组或矩阵里面元素个数/(m或n)

print(np.arange(10))

np.arange(10).reshape(-1,5)

04ba130ecb6c94d883cfe77218cea947.png

print(np.arange(10))

np.arange(10).reshape(5,-1)

26bfa9c097aad9aa2302b7f2c530eec7.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值