Python数据分析—Pandas中的Series

一、Series介绍

Series是一维数组型对象,包含了一个值序列,并且包含了数据标签,称为索引。

二、Series数组创建

pd.Series(data=None,index=None,dtype=None,name=None,copy=False)

参数作用
data创建数组的数据
index指定索引
dtype数组数据类型
name数组名称
copy是否拷贝

1、根据列表创建

s1=pd.Series([1,2,3,4])
s1
0    1
1    2
2    3
3    4
dtype: int64

可指定对应索引值

s2=pd.Series([1,2,3,4],index=['a','b','c','d'])
s2
a    1
b    2
c    3
d    4
dtype: int64

索引可重复

s3=pd.Series([1,2,3,4],index=['a','a','c','d'])
s3
a    1
a    2
c    3
d    4
dtype: int64

但是索引个数与值个数必须一致

s4=pd.Series([1,2,3,4],index=['a','a','c'])
s4
ValueError: Length of passed values is 4, index implies 3.

2、根据字典创建

dict={'name':'wj','age':18,'class':'one'}
s5=pd.Series(dict)
s5
name      wj
age       18
class    one
dtype: object

可构建索引列表,没有的索引赋值为NaN,不会覆盖原来的值

ind=['abc','name','age']
s6=pd.Series(dict,index=ind)
s6
abc     NaN
name     wj
age      18
dtype: object

三、数据类型

创建时可指定数据类型

s7=pd.Series(range(5),dtype='float')
s7
0    0.0
1    1.0
2    2.0
3    3.0
4    4.0
dtype: float64

查看数据类型

s7.dtype   # dtype('float64')

修改数据类型

s7.astype('int')
0    0
1    1
2    2
3    3
4    4
dtype: int32

四、设置数组名字

1、数组名字

s8=pd.Series(range(3),name='s_name')
s8
0    0
1    1
2    2
Name: s_name, dtype: int64

2、索引名字

s8.index.name='i_name'
s8
i_name
0    0
1    1
2    2
Name: s_name, dtype: int64

五、预览数据

s9=pd.Series(range(100))
print(s9.head())   # 默认查看前5的数据,n可传入修改
print(s9.tail())   # 默认查看后5的数据,n可传入修改

如果想预览全部数据,可使用以下代码,但慎重使用,数据量过大会卡死

#显示所有列
pd.set_option('display.max_columns', None)

#显示所有行
pd.set_option('display.max_rows', None)

#设置value的显示长度为100,默认为50
pd.set_option('max_colwidth',100)

六、索引与值

查看索引

s1.index
# RangeIndex(start=0, stop=4, step=1)

查看值序列

s1.values
# array([1, 2, 3, 4], dtype=int64)

注意:索引不可变,不能修改

s1.index[1]='a'
# TypeError: Index does not support mutable operations

七、索引与切片

查看数据

# 根据标签取值
s2['a']
# 根据索引取值
s2[0]
# 根据标签取值
s2.loc['a']
# 根据索引取值
s2.iloc[0]

挨个查看:用神奇索引

s2[['a','c']]
s2[[0,2]]
a    1
c    3
dtype: int64

连续查看

s2[:3]
s2.iloc[:3]
s2['a':'c']   # 切片使用标签也可,但注意是双闭合区间
a    1
b    2
c    3
dtype: int64

布尔索引取值

s2[s2>2]
c    3
d    4
dtype: int64

与标量进行运算

s2 * 2
a    2
b    4
c    6
d    8
dtype: int64

in 判断是否在数组里,但只能判断标签,不能判断序列值

print(1 in s2)    # False
print('a' in s2)  # True

八、Series运算

当数组有共同索引时,共同索引对应位置运算,其他填充NaN

ss1=pd.Series([1,2,3,4],index=['a','b','c','d'])
ss2=pd.Series([5,6,7,8,9,10],index=['a','b','c','d','e','f'])

ss1 + ss2
a     6.0
b     8.0
c    10.0
d    12.0
e     NaN
f     NaN
dtype: float64

当数组不存在共同索引时,全部填充NaN

ss3=pd.Series([1,2,3],index=['x','y','z'])
ss1 + ss3
a   NaN
b   NaN
c   NaN
d   NaN
x   NaN
y   NaN
z   NaN
dtype: float64
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值