前言
pandas与numpy的最大区别就是索引,pandas中索引是显式的,通过索引可以实现各种操作。
pandas中索引
![](https://img-blog.csdnimg.cn/img_convert/05ff68105d1294f196f7cd644f0f7c6d.png)
Pandas中索引属性
对DataFrame:
![](https://img-blog.csdnimg.cn/img_convert/7306b077e351ff69c80fdf67f660610e.png)
df对应的列和行index属性:
df.columns
df.index
Pandas中索引基础
![](https://img-blog.csdnimg.cn/img_convert/420ba0485a4408fff35d1f8092b9bbcd.png)
Pandas中的索引
轴标记的作用:
![](https://img-blog.csdnimg.cn/img_convert/9b2ba660d18adf6fc8c0db20dfc1e6d5.png)
![](https://img-blog.csdnimg.cn/img_convert/8f4cb3b7e9aa271c99f6e7cc3dc28e79.png)
![](https://img-blog.csdnimg.cn/img_convert/df012bee3898ece02ce79d34324f0eb5.png)
注意事项:
![](https://img-blog.csdnimg.cn/img_convert/3e4f9a2feb2b81c4f86f7ce5963a46da.png)
对Series而言,Series[label]返回的是对应label的单个值,Series[slicing]返回的是对应slicing的切片子Series;
对DataFrame而言,DataFrame[label]返回的是对应label的列的Series,DataFrame[slicing]返回的是对应行slicing的切片子DataFrame
DataFrame.loc[slicing]与DataFrame.iloc[slicing]的区别
DataFrame.loc[slicing]:
When slicing, thestart bound is included, AND the stop bound is included
DataFrame.iloc[slicing]:
When slicing, the start bounds is included, while theupper bound is excluded
Appendingoperation:
The.loc/[] operations can perform enlargement when setting a non-existant key forthat axis.
索引注意事项
type(df[“label”]) # pd.Series()
type(df[[“label”]]) # pd.DataFrame()
label和position混用问题
不能一个轴使用label,另一个轴使用position
pandas中的索引基础
![](https://img-blog.csdnimg.cn/img_convert/104e7b78c735e7cdacbe8310fa145bfb.png)
将列变成索引或将索引变成列
列变成行索引
df=df.set_index('date')
df.index=df.iloc[:,n]
行变成列索引
df.columns = df.iloc[n,:]
df = df.rename(index={}, columns={})
行索引变成列
df['index'] = df.index
df.reset_index(level=0, inplace=True)
df.reset_index(level=['tick', 'obs'])
df['si_name'] =df.index.get_level_values('si_name') #si_name is the name of the subindex
Series转DataFrame
series.to_frame()
只是将series对象转化为dataframe对象
pandas中index操作(重要)
df.set_index()
![](https://img-blog.csdnimg.cn/img_convert/08b0dffa00f03934665ca6835adf9432.png)
df.reset_index()
![](https://img-blog.csdnimg.cn/img_convert/ccabe549b446a278f2ccec29c94ab85c.png)
df.reindex()
![](https://img-blog.csdnimg.cn/img_convert/9ef1cfb5aa75d318e4faa4bd8b47a6c7.png)
改变索引值(index或columns)
直接修改属性
df.columns=[]
df.index=[]
使用rename或rename_axis函数
![](https://img-blog.csdnimg.cn/img_convert/f32e6f51bd4aa418212cdc4d34e320c0.png)
![](https://img-blog.csdnimg.cn/img_convert/732e08e615a3c78b78996e7b4803fcd7.png)
修改pandas中index或columns的名字
直接修改
![](https://img-blog.csdnimg.cn/img_convert/99e91625ea1c84cd338634d2bad83bae.png)
使用rename方法
![](https://img-blog.csdnimg.cn/img_convert/aef7dd47ac91271233c0238aa0e53d9c.png)
pandas中查看Series和DataFrame的索引值
![](https://img-blog.csdnimg.cn/img_convert/57e758505d6cd322e48f87551e46f0ce.png)
pandas中将pandas.index转化为其他类型
![](https://img-blog.csdnimg.cn/img_convert/1d07cc3863d12d1c50b1b765c112eff6.png)