Pandas入门Series


Series数组

导入pandas库

基本格式

import pandas as pd
s1 = pd.Series([1,2,3,4])
print(s1)

运行结果
0    1
1    2
2    3
3    4
dtype: int64

指定 Series 中每个数据值对应的标签(索引)使用index

import pandas as pd
s1 = pd.Series([1,2,3,4],index=['a','b','c','d'])
print(s1)

运行结果
a    1
b    2
c    3
d    4
dtype: int64

索引区别

s2 = 5	17 3  26 31
	 a	d  b  c  e  
	 0  1  2  3  4    

标签索引与位置索引

#标签索引
s1["b"]
运行结果
b	3
dtype: int64

#位置索引
s1[2]
运行结果
b	3
dtype: int64
标签索引s1["d":"c"] #包含结束值
d 17
b 3
c 26
dtype: int64


位置索引s1[1:3]		#不包含结束值
d 17
b 3
dtype: int64

索引取值时按照标签,切片取值按照位置

loc和iloc区别

loc-用标签索引

iloc-用位置索引

s2 = 5	17 3  26 31
	 1	3  5  7  9  #标签索引
	 0  1  2  3  4  #位置索引

loc - 用标签索引

s2.loc[1:3]

运行结果
1	5
3	17
dtype: int64

iloc-用位置索引

s2.iloc[1:3]

运行结果
3	17
5	3
dtype: int64

创建Series的另一种方式

给Series构造函数传字典

s3 = pd.Series({"数字1":1,"数字2":2,"数字3":3})

查看标签是否存在

"数字1" in s3
存在返回布尔值
True
不存在返回布尔值
False

修改Series值

s3["数字1"]  = 2		

s3.loc["数字1"] = 2	#标签索引

s3.iloc["0"] = 2	 #位置索引

根据条件筛选Series元素

s3[s3 > 1]
可利用逻辑符号and or but,&	| ~
s3[(s3 > 1) | (s3 < 5)]

文章作者: 暮雪(冷火)
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 暮雪(冷火) !
评论
  目录

嘘~ 正在从服务器偷取页面 . . .