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_time
Firefox	200	0.04
Chrome	200	0.02
Safari	404	0.07
IE10	404	0.08
Konqueror	301	1.00

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

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

  输出结果:

response_time
Firefox	0.04
IE10	0.08
Safari	0.07

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

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

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

http_status	response_time
Safari	404.0	0.07
Iceweasel	NaN	NaN
Comodo Dragon	NaN	NaN
IE10	404.0	0.08
Chrome	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	col3
0	0.0	1.0	2.0
1	3.0	4.0	5.0
2	NaN	NaN	NaN
3	NaN	NaN	NaN

  示例

b.reindex_like(a)

  输出结果:

col1	col2	col3
0	0	1	2
1	3	4	5

3 填充元素值

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

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

  示例

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

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

col1	col2	col3
0	0	1	2
1	3	4	5
2	3	4	5
3	3	4	5

  示例:

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

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

	col1	col2	col3
0	0.0	1.0	2.0
1	3.0	4.0	5.0
2	NaN	NaN	NaN
3	NaN	NaN	NaN

  示例:

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

  输出结果:

	col1	col2	col3
0	0	1	2
1	3	4	5
2	3	4	5
3	3	4	5

4 限制填充行数

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

  示例如下:

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

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

col1	col2	col3
0	0.0	1.0	2.0
1	3.0	4.0	5.0
2	3.0	4.0	5.0
3	NaN	NaN	NaN

5 重命名标签

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

  原始数据:df1 = 

col1	col2	col3
0	0	1	2
1	3	4	5

  示例如下:

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

  输出结果:

          c1        c2	c3
A	0	1	2
B	3	4	5

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

 

posted @ 2022-02-07 12:21  多发Paper哈  阅读(381)  评论(0编辑  收藏  举报
Live2D