python数据分析(9)——Pandas数据结构Series索引

类似于列表的位置下标索引:

s=pd.Series(np.random.rand(10))
print(s)
0    0.969396
1    0.981999
2    0.064227
3    0.751186
4    0.923914
5    0.596080
6    0.179902
7    0.330775
8    0.048466
9    0.556931
dtype: float64

print(s[3])   #下标索引
0.7511855138771393

下标索引并不完全和列表一样:

print(s[-1])   #这里就报错了
Traceback (most recent call last):

  File "<ipython-input-7-84238c3974a7>", line 1, in <module>
    print(s[-1])

  File "C:\Users\www12\Anaconda3\lib\site-packages\pandas\core\series.py", line 623, in __getitem__
    result = self.index.get_value(self, key)

  File "C:\Users\www12\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2560, in get_value
    tz=getattr(series.dtype, 'tz', None))

  File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item

KeyError: -1

标签索引:

s=pd.Series(np.random.rand(6),index=['a','b','c','d','e','f'])
print(s)
a    0.635180
b    0.471829
c    0.859320
d    0.505514
e    0.500021
f    0.299368
dtype: float64
方法类似下标索引,用[]表示,内容写上index,注意index是字符串
print(s['a'])
0.6351798913911209

print(s[['a','b']])
a    0.635180
b    0.471829
dtype: float64

多个标签索引用[[]]表示,[]表示一个列表
标签索引可以不按照index的顺序来,结果会生成新的数组

切片:

print(s[1:5])    #下标,左闭右开
b    0.471829
c    0.859320
d    0.505514
e    0.500021
dtype: float64

print(s['a':'c'])   #标签,左闭右闭
a    0.635180
b    0.471829
c    0.859320
dtype: float64

布尔索引

s=pd.Series(np.random.rand(6)*100,index=['a','b','c','d','e','f'])
print(s)
a    61.803796
b    45.965736
c    89.229410
d    61.375478
e    20.890655
f     8.225829
dtype: float64

s[4]=None
bs1=s>50

print(bs1)   #得到一个布尔型的数组
a     True
b    False
c     True
d     True
e    False
f    False
dtype: bool



bs2=s.isnull()   #判断是否为空值
bs3=s.notnull()  #判断是否不是空值

print(bs2)
print(bs3)
a    False
b    False
c    False
d    False
e     True
f    False
dtype: bool
a     True
b     True
c     True
d     True
e    False
f     True
dtype: bool

以上就是Series的索引方法,应当注意下标索引和标签索引和切片的区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值