Pandas中DataFrame的重新索引实例分析(dataframe,pandas,开发技术)

时间:2024-05-03 03:09:38 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

Pandas DataFrame之重新索引

1.reindex可以对行和列索引

默认对行索引,加上关键字columns对列索引。

importpandasaspddata=[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]df=pd.DataFrame(data,index=['d','b','c','a'])print(df)

Pandas中DataFrame的重新索引实例分析

默认对列索引:如果是新的索引名将会用NaN

df=df.reindex(['a','b','c','d','e'])print(df)

Pandas中DataFrame的重新索引实例分析

加上关键字columns对列重新索引:

df=df.reindex(columns=[2,1,3,4,0])print(df)

Pandas中DataFrame的重新索引实例分析

2.reindex插值处理

对于index为有序的数据,我们有时候可能会进行一些插值处理,只需要在reindex加上method参数即可,参数如下表

Pandas中DataFrame的重新索引实例分析

(图片来源:截图于 利用python进行数据分析 Wes McKinney 著)

例子:

importpandasaspddata=[[1,1,1,1],[2,2,2,2],[3,3,3,3]]df=pd.DataFrame(data,index=range(3))print(df)df=df.reindex([0,1,2,3,4,5],method='ffill')print('--------------')print(df)

Pandas中DataFrame的重新索引实例分析

reindex函数的相关参数:

Pandas中DataFrame的重新索引实例分析

Pandas DataFrame重置索引案例

importpandasaspdimportnumpyasnpa=pd.DataFrame(np.random.randint(1,10,20).reshape(4,5))print(a)01234013276182272226625341689b=a.sort_values(by=4)print(b)01234182272226625013276341689###重置索引:方法1c=a.sort_values(by=4,ignore_index=True)print(c)01234082272126625213276341689###重置索引:方法2d=b.reset_index(drop=True)print(d)01234082272126625213276341689
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Pandas中DataFrame的重新索引实例分析的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:pytorch tensor计算三通道均值方式是什么下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18