pandas中的索引index操作总结

前言

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操作(重要)

  1. df.set_index()

  1. df.reset_index()

  1. df.reindex()

改变索引值(index或columns)

  1. 直接修改属性

df.columns=[]

df.index=[]

  1. 使用rename或rename_axis函数

修改pandas中index或columns的名字

直接修改

使用rename方法

pandas中查看Series和DataFrame的索引值

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

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年11月29日
下一篇 2023年11月29日

相关推荐