Python-索引、切片的区间闭合问题

2018-06-23  本文已影响0人  去他山捡石头
#range()生成器,左闭右开
for i in range(1,3):
    print(i)

#输出结果为:
1
2
  1. Pandas中,利用标签的切片运算是末端包含的,比如:
import numpy as np
import pandas as pd
arr = pd.Series(np.arange(5),index=['a','b','c','d','e'])
print(arr)    #输出原数组作为参考
print('------')
print(arr[:2])  #利用默认的序号进行切片,[:2]结果为0,1,不包含2,即末端不包含
print('------')
print(arr[:'c'])  #利用标签进行切片,[:'c']结果为a,b,c,包含c,即末端包含

#输出结果为:
a    0
b    1
c    2
d    3
e    4
dtype: int32
------
a    0
b    1
dtype: int32
------
a    0
b    1
c    2
dtype: int32
  1. Pandas中,对行和列的数据同时进行索引时,是末端包含
df = pd.DataFrame(np.random.randn(3,3))
print('用序号做索引,且只选取列,末端不包含:\n',df[:2])
print('------')
print('用序号做索引,同时选取行和列,末端包含:\n',df.ix[:2,:1])

#输出结果为:
用序号做索引,且只选取列,末端不包含:
           0         1         2
0  1.365432 -0.716718  1.346831
1 -1.321862 -0.713850  1.295334
------
用序号做索引,同时选取行和列,末端包含:
           0         1
0  1.365432 -0.716718
1 -1.321862 -0.713850
2 -0.006941  0.936674

学习笔记,后续会持续更新该主题,如果你有更好的方案,欢迎留言讨论。

上一篇 下一篇

猜你喜欢

热点阅读