索引对象
pandas的索引对象是数据标签的容器。在创建序列或数据框的时候,数组或者其他表示数据标签的有序列会自动的转换成索引对象。
>>> s
a 0.694635
b 0.068107
c 0.302411
d 0.044751
a 0.858449
dtype: float64
>>> s.index
Index(['a', 'b', 'c', 'd', 'a'], dtype='object')
>>> s.index[1:3]
Index(['b', 'c'], dtype='object')
索引对象是不可以被修改的s.index[1:2]='f
是会报错的。
可以把索引对象通过赋值的方式赋给其他数据结构
>> ss = pd.Series(range(3), index=s.index[1:4])
>>> ss
b 0
c 1
d 2
dtype: int64
如果个数相等的情况下直接赋值,索引对象是相同的,并不会生成一个新的索引对象。
核心的基本函数
- head(n):展示前n行数据
- tail(n):展示后n行数据
- shape属性返回数组的形状,values属性返回实际的数据。
- reindex()可以改变索引并且创建一个新的对象
>>> s = pd.Series(range(4), index=['a','b','c','d'])
>>> s
a 0
b 1
c 2
d 3
dtype: int64
>>> s.reindex([1,2,3,4])
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
>>> s.reindex([1,2,3,4], fill_value=0)
1 0
2 0
3 0
4 0
dtype: int64
可以看到,由于之前没有标签,所有的数据都是NaN,用fill_value可以填充值。(使用s = s.reindex(……))才会改变s
也可以通过Index参数和columns改变行列标签。
- rename可以改变列标签名
trainData.rename(columns={'Name':'Title'}, inplace=True)
这里就是把trainData的列名从Name,改到了Title