Lesson8——Pandasreindex重置索引

博客 动态
0 215
羽尘
羽尘 2022-02-07 12:55:02
悬赏:0 积分 收藏

Lesson8——Pandas reindex重置索引

pandas目录

1 简介

  重置索引(reindex)可以更改原 DataFrame 的行标签或列标签,并使更改后的行、列标签与 DataFrame 中的数据逐一匹配。通过重置索引操作,您可以完成对现有数据的重新排序。如果重置的索引标签在原 DataFrame 中不存在,那么该标签对应的元素值将全部填充为 NaN

2 重置行列标签

  选取特定行、列

  示例:先构建数据

index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301],                  'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},                  index=index)df

  输出结果:

http_status	response_timeFirefox	200	0.04Chrome	200	0.02Safari	404	0.07IE10	404	0.08Konqueror	301	1.00

  示例:同时使用行、列标签选取数据。

new_index = ['Firefox', 'IE10', 'Safari']df.reindex(index=new_index,columns=['response_time'])

  输出结果:

response_timeFirefox	0.04IE10	0.08Safari	0.07

  示例:只使用行标签选取数据。

new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',             'Chrome']df.reindex(new_index)

  输出结果:不存在的行使用 NaN 代替。

http_status	response_timeSafari	404.0	0.07Iceweasel	NaN	NaNComodo Dragon	NaN	NaNIE10	404.0	0.08Chrome	200.0	0.02

  现有 a、b 两个 DataFrame 对象,如果想让 的行索引与 b 相同,您可以使用 reindex_like() 方法。

  示例如下:

a = pd.DataFrame(np.arange(6).reshape((2,3)),columns=['col1','col2','col3'])b = pd.DataFrame(np.arange(12).reshape((4,3)),columns=['col1','col2','col3'])a.reindex_like(b)

  输出结果:由于 a 的 size 小于 b ,所以 2 、3行不存在,用 NaN 代替。 

col1	col2	col30	0.0	1.0	2.01	3.0	4.0	5.02	NaN	NaN	NaN3	NaN	NaN	NaN

  示例

b.reindex_like(a)

  输出结果:

col1	col2	col30	0	1	21	3	4	5

3 填充元素值

  reindex_like()  提供了一个可选的参数 method,使用它来填充相应的元素值,参数值介绍如下:

  • pad/ffill:向前填充值;
  • bfill/backfill:向后填充值;
  • nearest:从距离最近的索引值开始填充。

  示例

a.reindex_like(b,method='ffill')

  输出结果:相当于从有数据的最后一行复制数据到下面的每一行。

col1	col2	col30	0	1	21	3	4	52	3	4	53	3	4	5

  示例:

a.reindex_like(b,method='bfill')

  输出结果:相当于从最后一行复制数据到上面的行。

	col1	col2	col30	0.0	1.0	2.01	3.0	4.0	5.02	NaN	NaN	NaN3	NaN	NaN	NaN

  示例:

a.reindex_like(b,method='nearest')

  输出结果:

	col1	col2	col30	0	1	21	3	4	52	3	4	53	3	4	5

4 限制填充行数

  reindex_like()  还提供了一个额外参数 limit,该参数用来控制填充的最大行数。

  示例如下:

a.reindex_like(b,method='ffill',limit=1)

  输出结果:这里只填充了 1 行。

col1	col2	col30	0.0	1.0	2.01	3.0	4.0	5.02	3.0	4.0	5.03	NaN	NaN	NaN

5 重命名标签

  rename() 方法允许您使用某些映射 (dict或Series) 或任意函数来对行、列标签重新命名。

  原始数据:df1 = 

col1	col2	col30	0	1	21	3	4	5

  示例如下:

df1.rename(columns={'col1':'c1','col2':'c2','col3':'c3'},index={0:'A',1:'B'})

  输出结果:

          c1        c2	c3A	0	1	2B	3	4	5

  rename() 方法提供了一个 inplace 参数,默认值为 False,表示拷贝一份原数据,并在复制后的数据上做重命名操作。若 inplace=True 则表示在原数据的基础上重命名。

 

因上求缘,果上努力~~~~ 作者:cute_Learner,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/15867390.html

posted @ 2022-02-07 12:21 cute_Learner 阅读(3) 评论(0) 编辑 收藏 举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员