pandas rename 功能

  • 在使用 pandas 的过程中经常会用到修改列名称的问题,会用到 rename 或者 reindex 等功能,每次都需要去查文档
  • 当然经常也可以使用 df.columns重新赋值为某个列表
  • 用 rename 则可以轻松应对 pandas 中修改列名的问题

导入常用的数据包

import pandas as pd
import numpy as np

构建一个 含有multiIndex的 Series

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)

s.index
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
names=['first', 'second'])

查看 s

s
first  second
bar one -0.073094
two -0.449141
baz one 0.109093
two -0.033135
foo one 1.315809
two -0.887890
qux one 2.255328
two -0.778246
dtype: float64

使用set_names可以将 index 中的名称进行更改

s.index.set_names(['L1', 'L2'], inplace=True)

s
L1   L2
bar one 0.037524
two -0.178425
baz one -0.778211
two 1.440168
foo one 0.314172
two 0.710597
qux one 1.197275
two 0.527058
dtype: float64
s.index
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
names=['L1', 'L2'])

同样可以使用 rename 将Series 修改回来

s.index.rename(['first','second'],inplace= True)
s
first  second
bar one 0.037524
two -0.178425
baz one -0.778211
two 1.440168
foo one 0.314172
two 0.710597
qux one 1.197275
two 0.527058
dtype: float64

使用reset_index 可以将 index 中的两列转化为正常的列

s.reset_index()

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
first second 0
0 bar one 0.037524
1 bar two -0.178425
2 baz one -0.778211
3 baz two 1.440168
4 foo one 0.314172
5 foo two 0.710597
6 qux one 1.197275
7 qux two 0.527058

可以使用 pivot_table 恢复成一开始的样子,将两列重新作为 index 展示出来

s.reset_index().pivot_table(index=['first','second'],values=0,aggfunc=lambda x:x)

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
0
first second
bar one 0.037524
two -0.178425
baz one -0.778211
two 1.440168
foo one 0.314172
two 0.710597
qux one 1.197275
two 0.527058

同样可以使用最简单的方式进行更改 index 中的名称

s.index.names=['first1','second1'] ## 此操作,相当于直接赋值,会更改 s
s.index
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
names=['first1', 'second1'])
s
first1  second1
bar one 0.037524
two -0.178425
baz one -0.778211
two 1.440168
foo one 0.314172
two 0.710597
qux one 1.197275
two 0.527058
dtype: float64
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,                    'B' : ['A', 'B', 'C'] * 4,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D' : np.random.randn(12),
'E' : np.random.randn(12)})
df.head()

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
A B C D E
0 one A foo 0.664180 -0.107764
1 one B foo -0.833609 0.008083
2 two C foo 0.117919 -1.365583
3 three A bar -0.116776 -1.201934
4 one B bar -1.315190 -0.157779
df.pivot_table(index=['A','C'],values=['D'],columns='B',aggfunc=np.sum,fill_value='unknown')

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead tr th {
text-align: left;
} .dataframe thead tr:last-of-type th {
text-align: right;
}
D
B A B C
A C
one bar 2.71452 -1.31519 0.0231296
foo 0.66418 -0.833609 -0.96451
three bar -0.116776 unknown 0.450891
foo unknown 0.012846 unknown
two bar unknown 0.752643 unknown
foo 0.963631 unknown 0.117919
df1 =df.pivot_table(index=['A','C'],values=['D'],columns='B',aggfunc=np.sum,fill_value='unknown')
df1.index
MultiIndex(levels=[['one', 'three', 'two'], ['bar', 'foo']],
labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
names=['A', 'C'])
df1.index.names=['first','second']
df1

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead tr th {
text-align: left;
} .dataframe thead tr:last-of-type th {
text-align: right;
}
D
B A B C
first second
one bar 2.71452 -1.31519 0.0231296
foo 0.66418 -0.833609 -0.96451
three bar -0.116776 unknown 0.450891
foo unknown 0.012846 unknown
two bar unknown 0.752643 unknown
foo 0.963631 unknown 0.117919
df1_stack=df1.stack()
df1_stack.index.names=['first','second','third']
df1_stack

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
D
first second third
one bar A 2.71452
B -1.31519
C 0.0231296
foo A 0.66418
B -0.833609
C -0.96451
three bar A -0.116776
B unknown
C 0.450891
foo A unknown
B 0.012846
C unknown
two bar A unknown
B 0.752643
C unknown
foo A 0.963631
B unknown
C 0.117919
df1_stack.columns=['总和']
df1_stack

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
总和
first second third
one bar A 2.71452
B -1.31519
C 0.0231296
foo A 0.66418
B -0.833609
C -0.96451
three bar A -0.116776
B unknown
C 0.450891
foo A unknown
B 0.012846
C unknown
two bar A unknown
B 0.752643
C unknown
foo A 0.963631
B unknown
C 0.117919
df2 = df1_stack.reset_index()
df2.set_index('first')

.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}

.dataframe tbody tr th {
vertical-align: top;
} .dataframe thead th {
text-align: right;
}
second third 总和
first
one bar A 2.71452
one bar B -1.31519
one bar C 0.0231296
one foo A 0.66418
one foo B -0.833609
one foo C -0.96451
three bar A -0.116776
three bar B unknown
three bar C 0.450891
three foo A unknown
three foo B 0.012846
three foo C unknown
two bar A unknown
two bar B 0.752643
two bar C unknown
two foo A 0.963631
two foo B unknown
two foo C 0.117919

pandas功能使用rename, reindex, set_index 详解的更多相关文章

  1. ES6,ES2105核心功能一览,js新特性详解

    ES6,ES2105核心功能一览,js新特性详解 过去几年 JavaScript 发生了很大的变化.ES6(ECMAScript 6.ES2105)是 JavaScript 语言的新标准,2015 年 ...

  2. 【python库模块】Python subprocess模块功能与常见用法实例详解

    前言 这篇文章主要介绍了Python subprocess模块功能与常见用法,结合实例形式详细分析了subprocess模块功能.常用函数相关使用技巧. 参考 1. Python subprocess ...

  3. Pandas系列(六)-时间序列详解

    内容目录 1. 基础概述 2. 转换时间戳 3. 生成时间戳范围 4. DatetimeIndex 5. DateOffset对象 6. 与时间序列相关的方法 6.1 移动 6.2 频率转换 6.3 ...

  4. Pandas透视表(pivot_table)详解

    介绍 也许大多数人都有在Excel中使用数据透视表的经历,其实Pandas也提供了一个类似的功能,名为pivot_table.虽然pivot_table非常有用,但是我发现为了格式化输出我所需要的内容 ...

  5. Linux下针对路由功能配置iptables的方法详解

    作为公司上网的路由器需要实现的功能有nat地址转换.dhcp.dns缓存.流量控制.应用程序控制,nat地址转换通过iptables可以直 接实现,dhcp服务需要安装dhcpd,dns缓存功能需要使 ...

  6. 短视频 SDK 功能点技术实现方式详解

    第三方短视频解决方案作为快速切入短视频行业的首选方式,选择一款功能齐全.性能优异的短视频解决方案十分重要. 今天我们来谈谈短视频 SDK 6大重要功能点及其技术实现方式. 短视频拍摄 断点续拍 指在拍 ...

  7. Pandas系列(一)-Series详解

    一.初始Series Series 是一个带有 名称 和索引的一维数组,既然是数组,肯定要说到的就是数组中的元素类型,在 Series 中包含的数据类型可以是整数.浮点.字符串.Python对象等. ...

  8. centos6.5环境自动化运维之puppet实现nginx反向代理功能及puppet安装配置详解

    puppet是一种Linux.Unix.windows平台的集中配置管理系统,使用自有的puppet描述语言,可管理配置文件.用户.cron任务.软件包.系统服务等.puppet把这些系统实体称之为资 ...

  9. Pandas高级教程之:plot画图详解

    目录 简介 基础画图 其他图像 bar stacked bar barh Histograms box Area Scatter Hexagonal bin Pie 在画图中处理NaN数据 其他作图工 ...

随机推荐

  1. 【】tensorflow学习笔记

    一.看懂了Tensor("mul_1:0", shape=(), dtype=int32)中的shape https://blog.csdn.net/u013378306/arti ...

  2. 解析 ViewTreeObserver 源码(下)

    继上篇内容,本文介绍 ViewTreeObserver 的使用,以及体会其所涉及的观察者模式,期间会附带回顾一些基础知识.最后,我们简单聊一下 Android 的消息传递,附高清示意图,轻松捋清整个传 ...

  3. rvs产生服从指定分布的随机数 pdf概率密度函数 cdf累计分布函数 ppf 分位点函数

    统计工作中几个常用用法在python统计函数库scipy.stats的使用范例. 正态分布以正态分布的常见需求为例了解scipy.stats的基本使用方法. 1.生成服从指定分布的随机数 norm.r ...

  4. NoSQL简单介绍

    这里介绍一下如今经常使用的NoSQL以及各自的特点. NoSQL是2009年突然发展起来的.如今趋于稳定的状态,市场上也有了一些比較成熟的产品. 传统的关系型数据库为了保证通用性的设计而带来了功能复杂 ...

  5. C# ReaderWriterLockSlim 实现

    其实ReaderWriterLockSlim的实现前段时间看了,当时不打算记录下来的,因为它的实现实在System.Core项目里面,而不是mscorlib项目.按照惯例我们还是先看看网上的一些说法吧 ...

  6. Git上传空文件夹

    git上传的文件夹为空的时候 1,先删除空的文件夹 参考:https://www.cnblogs.com/wang715100018066/p/9694532.html 2,这个只能说是技巧不能说是方 ...

  7. [CSS] Useful CSS tool for Web designer and developer

    1. Color Picker (Chrome) You might know how to use color picker in Chrome, recently there is a featu ...

  8. grid - 隐式命名网格线名称

    1.隐式的指定网格线反向指定了隐式的网格区域名称,命名的网格区域隐式的命名了网格线名称. 指定网格区域会给网格区域边线添加隐式的网格线名称.这些网格线的命名是基于网格区域来命名,只是在网格区域名称的后 ...

  9. spring mvc 实战化项目之三板斧

    laravel实战化项目之三板斧 spring mvc 实战化项目之三板斧 asp.net mvc 实战化项目之三板斧 接上文希望从一张表(tb_role_info 用户角色表)的CRUD展开spri ...

  10. cookie 跨域解决方法

    1.Nginx 正向和反向代理的区别 正向代理和反向代理的区别:正向代理隐藏真实客户端,反向代理隐藏真实服务端,图示: 2.cookie跨域问题 因为cookie存在跨域问题,其中一个解决方法是,设置 ...