前言
pandas与numpy的最大区别就是索引,pandas中索引是显式的,通过索引可以实现各种操作。
pandas中索引

Pandas中索引属性
对DataFrame:

df对应的列和行index属性:
df.columns
df.index
Pandas中索引基础

Pandas中的索引
轴标记的作用:



注意事项:

对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中的索引基础

将列变成索引或将索引变成列
列变成行索引
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()

df.reset_index()

df.reindex()

改变索引值(index或columns)
直接修改属性
df.columns=[]
df.index=[]
使用rename或rename_axis函数


修改pandas中index或columns的名字
直接修改

使用rename方法

pandas中查看Series和DataFrame的索引值

pandas中将pandas.index转化为其他类型

文章详细介绍了Pandas与NumPy在索引上的主要区别,强调了Pandas中显式的索引特性。文中讨论了DataFrame和Series的索引属性,如`df.columns`和`df.index`,以及轴标记的作用。重点讲述了索引操作,包括切片、loc和iloc的使用规则,以及如何通过set_index和reset_index改变索引。此外,还提到了reindex、rename等方法用于调整索引,并展示了将索引转换为列和列转换为索引的操作。

3282

被折叠的 条评论
为什么被折叠?



