示例代碼:php
print(type(ser_obj.index))
print(type(df_obj2.index))
print(df_obj2.index)
運行結果:css
<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')
示例代碼:python
# 索引對象不可變
df_obj2.index[0] = 2
運行結果:安全
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-7f40a356d7d1> in <module>()
1 # 索引對象不可變
----> 2 df_obj2.index[0] = 2
/Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value)
1402
1403 def __setitem__(self, key, value):
-> 1404 raise TypeError("Index does not support mutable operations")
1405
1406 def __getitem__(self, key):
TypeError: Index does not support mutable operations
示例代碼:ruby
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
運行結果:bash
a 0 b 1 c 2 d 3 e 4 dtype: int64
ser_obj[‘label’], ser_obj[pos]
示例代碼:app
# 行索引
print(ser_obj['b'])
print(ser_obj[2])
運行結果:dom
1 2
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操做時,是包含終止索引的。flex
示例代碼:ui
# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d'])
運行結果:
b 1 c 2 dtype: int64 b 1 c 2 d 3 dtype: int64
ser_obj[[‘label1’, ’label2’, ‘label3’]]
示例代碼:
# 不連續索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
運行結果:
a 0 c 2 e 4 dtype: int64 a 0 e 4 dtype: int64
示例代碼:
# 布爾索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])
運行結果:
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
示例代碼:
import numpy as np
df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj.head())
運行結果:
a b c d
0 -0.241678 0.621589 0.843546 -0.383105
1 -0.526918 -0.485325 1.124420 -0.653144
2 -1.074163 0.939324 -0.309822 -0.209149
3 -0.716816 1.844654 -2.123637 -1.323484
4 0.368212 -0.910324 0.064703 0.486016
df_obj[[‘label’]]
示例代碼:
# 列索引
print(df_obj['a']) # 返回Series類型
運行結果:
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
df_obj[[‘label1’, ‘label2’]]
示例代碼:
# 不連續索引
print(df_obj[['a','c']])
運行結果:
a c
0 -0.241678 0.843546
1 -0.526918 1.124420
2 -1.074163 -0.309822
3 -0.716816 -2.123637
4 0.368212 0.064703
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果:
注意,按索引名切片操做時,是包含終止索引的。
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果:
示例代碼:
運行結果: