pandas记载
1.构造Series和DataFrame对象
Series和DataFrame是pandas的基本对象,下面来演示下如何构造它们:
import pandas as pd
#构造series对象
obj_series=pd.Series(range(3),index=['one','two','three'])
#构造DataFrame对象
data={'one':[1,11,111],'two':[2,22,222],'three':[3,33,333]}
obj_dataframe=pd.DataFrame(data,index=['a','b','c'])
输出格式如下:
这是obj_series对象和obj_dataframe对象;
构造Series和DataFrame的方法还有很多,基本上由字典,列表,数组格式所构成的数据都可以构造。
2.重建索引方法
- reindex() :可以将索引进行排序;
我们先构造一个DataFrame对象
import numpy as np
import pandas as pd
frame=pd.DataFrame(np.arange(9).reshape((3,3)),index=['one','two','three'],
columns=['a','b','c'])
frame
输出如下:
接下来我们使用reindex()来重置索引:
frame1=frame.reindex(index=['three','one','two','four'],columns=['d','c','a'])
frame1
2. loc() :简便的重建索引方法
frame.loc[['one','two','four','three'],['c','a','b','no']]
3.drop()方法:删除一列或一行
还是利用frame对象,在drop()方法中我们可以通过axis=0或1来确定选中的是列还是行,axis=1代表选中的是列,反制axis=0代表行,实例如下:
4.pandas对象索引
1.简单索引:
选择行:frame[ : ‘行名称’]
选择列:frame[‘列名称’],frame[['列名称1’,‘列名称2’]]
接下来演示如何用简单索引选择列:
简单索引选择行:
2.利用loc(),iloc() 进行选择:
loc(), iloc()可以让DataFrame以narray数组的方式进行选择: