pandas调整列的顺序以及添加列的实现
作者:python小工具 发布时间:2022-09-21 12:31:10
标签:pandas,列顺序,添加列
在对excel的操作中,调整列的顺序以及添加一些列也是经常用到的,下面我们用pandas实现这一功能。
1、调整列的顺序
>>> df = pd.read_excel(r'D:/myExcel/1.xlsx')
>>> df
A B C D
0 bob 12 78 87
1 millor 15 92 21
>>> df.columns
Index(['A', 'B', 'C', 'D'], dtype='object')
# 这是最简单常用的一种方法,相当于指定列名让pandas
# 从df中获取
>>> df[['A', 'D', 'C', 'B']]
A D C B
0 bob 87 78 12
1 millor 21 92 15
# 这也是可以的
>>> df[['A', 'A', 'A', 'A']]
A A A A
0 bob bob bob bob
1 millor millor millor millor
2、添加某一列或者某几列
(1)直接添加
>>> df['E']=[1, 2]
>>> df
A B C D E
0 bob 12 78 87 1
1 millor 15 92 21 2
(2)调用assign方法。该方法善于根据已有的列添加新的列,通过基本运算,或者调用函数
>>> df
A B C D
0 bob 12 78 87
1 millor 15 92 21
# 其中E是列名,根据B列-C列的值得到
>>> df.assign(E=df['B'] - df['C'])
A B C D E
0 bob 12 78 87 -66
1 millor 15 92 21 -77
# 添加两列也可以
>>> df.assign(E=df['B'] - df['C'], F=df['B'] * df['C'])
A B C D E F
0 bob 12 78 87 -66 936
1 millor 15 92 21 -77 1380
哈哈,以上就是pandas关于调整列的顺序以及新增列的用法
补充:pandas修改DataFrame中的列名&调整列的顺序
修改列名:
直接调用接口:
df.rename()
看一下接口中的定义:
def rename(self, *args, **kwargs):
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
See the :ref:`user guide <basics.rename>` for more.
Parameters
----------
mapper, index, columns : dict-like or function, optional
dict-like or functions transformations to apply to
that axis' values. Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index`` and
``columns``.
axis : int or str, optional
Axis to target with ``mapper``. Can be either the axis name
('index', 'columns') or number (0, 1). The default is 'index'.
copy : boolean, default True
Also copy underlying data
inplace : boolean, default False
Whether to return a new DataFrame. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
Returns
-------
renamed : DataFrame
See Also
--------
pandas.DataFrame.rename_axis
Examples
--------
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
"""
axes = validate_axis_style_args(self, args, kwargs, 'mapper', 'rename')
kwargs.update(axes)
# Pop these, since the values are in `kwargs` under different names
kwargs.pop('axis', None)
kwargs.pop('mapper', None)
return super(DataFrame, self).rename(**kwargs)
注意:
一个*,输入可以是数组、元组,会把输入的数组或元组拆分成一个个元素。
两个*,输入必须是字典格式
示例:
>>>import pandas as pd
>>>a = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]})
>>> a
A B C
0 1 4 7
1 2 5 8
2 3 6 9
#将列名A替换为列名a,B改为b,C改为c
>>>a.rename(columns={'A':'a', 'B':'b', 'C':'c'}, inplace = True)
>>>a
a b c
0 1 4 7
1 2 5 8
2 3 6 9
调整列的顺序:
如:
>>> import pandas
>>> dict_a = {'user_id':['webbang','webbang','webbang'],'book_id':['3713327','4074636','26873486'],'rating':['4','4','4'],
'mark_date':['2017-03-07','2017-03-07','2017-03-07']}
>>> df = pandas.DataFrame(dict_a) # 从字典创建DataFrame
>>> df # 创建好的df列名默认按首字母顺序排序,和字典中的先后顺序并不一样,字典中'user_id','book_id','rating','mark_date'
book_id mark_date rating user_id
0 3713327 2017-03-07 4 webbang
1 4074636 2017-03-07 4 webbang
2 26873486 2017-03-07 4 webbang
直接修改列名:
>>> df = df[['user_id','book_id','rating','mark_date']] # 调整列顺序为'user_id','book_id','rating','mark_date'
>>> df
user_id book_id rating mark_date
0 webbang 3713327 4 2017-03-07
1 webbang 4074636 4 2017-03-07
2 webbang 26873486 4 2017-03-07
就可以了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/weixin_45144170/article/details/105007711
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- python中的变量定义是很灵活的,很容易搞混淆,特别是对于class的变量的定义,如何定义使用类里的变量是我们维护代码和保证代码稳定性的关
- 问题:将文件夹a下任意命名的10个文件修改为如下图所示文件?代码:#coding:utf-8import ospath = "./
- 一、python压缩模块简介python直接通过内置压缩模块可以直接进行压缩文件的创建;内置模块 zipfile/rarfile 完成压缩文
- 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义cl
- 大家好,我是只谈技术不剪发的 Tony 老师。我们在开发 Oracle 数据库程序时,如果想要通过 PL/SQL 存储过程实现发送邮件的功能
- Ruby中有一个很方便的Struct类,用来实现结构体。这样就不用费力的去定义一个完整的类来仅仅用作访问属性。class Dog <
- 鼠标双击滚动屏幕,单击停止滚动,很多小说新闻网站都有这个很人性化的功能,阅读起小说、新闻来很方便,不用手动拉滚动条。js代码如下:<h
- 大家还记得我们在老版本中,对于线上环境配置中会把所有的 css 多打成一个文件:核心是使用了插件 extract-text-webpack-
- js中报404是经常出现的问题,下列是一些高频原因;<script src="${pageContext.request.c
- 5月3日晚,央视在《新闻联播》前播放了B站青年宣言片《后浪》,这是B站首次登陆央视黄金时段,今天在朋友圈陆续看到相关的视频。最早用B站的同学
- 目录outputoutput.pathoutput.publicPathwebpack-dev-server中的publicPathhtml
- 说明本文根据https://github.com/liuchengxu/blockchain-tutorial的内容,用python实现的,
- 【简介】django-admin.py是Django的一个用于管理任务的命令行工具。本文将描述它的大概用法。另外,在每一个Django pr
- 说在前面nodejs 读取数据库是一个异步操作,所以在数据库还未读取到数据之前,就会继续往下执行代码。最近写东西时,需要对数据库进行批量数据
- 相信很多人在使用Ajax与后台php页面进行交互的时候都碰到过中文乱码的问题。JSON作为一种轻量级的数据交换格式,备受亲睐,但是用PHP作
- 前言值类型:所有像int、float、bool和string这些类型都属于值类型,使用这些类型的变量直接指向存在内存中的值,值类型的变量的值
- 本文实例为大家分享了js实现简单放大镜特效的具体代码,供大家参考,具体内容如下先来看看效果:写放大镜之前我们先来了解一下定位:通常子绝父相
- 前言:在fastapi中,我们定义的查询参数是可以设置成:必选参数 or 可选参数。可选查询参数只要给查询参数的默认值设置为None,表示该
- 1 什么是嵌套循环所谓嵌套循环就是一个外循环的主体部分是一个内循环。内循环或外循环可以是任何类型,例如 while 循环或 for 循环。
- 两年前发表的《The visual design of Web 2.0》中提到“Rounded everything”,圆角因使人感觉舒适的