pandas Index对象的创建,、查、改、增、删和使用
import numpy as np
import pandas as pd
单层索引
1.1 创建
pd.Index(data, dtype = Object, name = None)
- name:一维列表
- dtype:索引元素的类型,默认为object型
- name:索引的名字,类似于列的名字
data = ['a','b','c']
data=pd.Index(data,name='name1')
data
Index(['a', 'b', 'c'], dtype='object', name='name1')
data.name
'name1'
data.values
array(['a', 'b', 'c'], dtype=object)
data.dtype
dtype('O')
data[0]
'a'
data[0:2]
Index(['a', 'b'], dtype='object', name='name1')
data[[0,2]]
# 列表,返回index
Index(['a', 'c'], dtype='object', name='name1')
1.3 改索引名
虽然索引的值是不能修改的,但是名字确是可以修改的。
data.name="new_name"
data
Index(['a', 'b', 'c'], dtype='object', name='new_name')
data.set_names("name",inplace=True)
data
Index(['a', 'b', 'c'], dtype='object', name='name')
1.4.1 按位置添加一行
data.insert(loc,value)
- loc 位置编号
- value 值
data.insert(2,"c")
Index(['a', 'b', 'c', 'c'], dtype='object', name='name')
1.4.2 尾部添加多行
Index.append(other)
- other:其他索引对象
data2=pd.Index(["b","c","d"])
data2
Index(['b', 'c', 'd'], dtype='object')
data.append(data)
Index(['a', 'b', 'c', 'a', 'b', 'c'], dtype='object', name='name')
1.4.2 并
Index.union(other)
data.union(data2)
Index(['a', 'b', 'c', 'd'], dtype='object')
1.5.1 按位置删除一行
Index.delete(loc)
- loc:位置编号
data=data.delete(0)
data
Index(['c'], dtype='object', name='name')
1.5.1 按位置删除一行
Index.delete(loc)
- loc:位置编号
data.drop(["c"])
Index([], dtype='object', name='name')
1.5.3 交
Index.intersection(other)
data.intersection(data2)
data2
Index(['b', 'c', 'd'], dtype='object')
2. 多层索引
2.1 创建
pd.MultiIndex.from_tuples(labels, names = None)
labels:元组或列表的列表;
names:名字的列表。
data = [('a','one'),('a','two'),('b','one')]
data=pd.MultiIndex.from_tuples(data,names=["name1","name2"])
data
MultiIndex(levels=[['a', 'b'], ['one', 'two']],
codes=[[0, 0, 1], [0, 1, 0]],
names=['name1', 'name2'])
s=pd.Series([1,2,3],index=data)
s
name1 name2
a one 1
two 2
b one 3
dtype: int64
s[0]
1
-