Pandas 数据框增、删、改、查、去重、抽样基本操作方法


Posted in Python onApril 12, 2018

总括

pandas的索引函数主要有三种:

loc 标签索引,行和列的名称

iloc 整型索引(绝对位置索引),绝对意义上的几行几列,起始索引为0

ix 是 iloc 和 loc的合体

at是loc的快捷方式

iat是iloc的快捷方式

建立测试数据集:

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c'],'c': ["A","B","C"]})
print(df)
 a b c
0 1 a A
1 2 b B
2 3 c C

行操作

选择某一行

print(df.loc[1,:])
a 2
b b
c B
Name: 1, dtype: object

选择多行

print(df.loc[1:2,:])#选择1:2行,slice为1
 a b c
1 2 b B
2 3 c C
print(df.loc[::-1,:])#选择所有行,slice为-1,所以为倒序
 a b c
2 3 c C
1 2 b B
0 1 a A
print(df.loc[0:2:2,:])#选择0至2行,slice为2,等同于print(df.loc[0:2:2,:])因为只有3行
 a b c
0 1 a A
2 3 c C

条件筛选

普通条件筛选

print(df.loc[:,"a"]>2)#原理是首先做了一个判断,然后再筛选
0 False
1 False
2  True
Name: a, dtype: bool
print(df.loc[df.loc[:,"a"]>2,:])
 a b c
2 3 c C

另外条件筛选还可以集逻辑运算符 | for or, & for and, and ~for not

In [129]: s = pd.Series(range(-3, 4))
In [132]: s[(s < -1) | (s > 0.5)]
Out[132]: 
0 -3
1 -2
4 1
5 2
6 3
dtype: int64

isin

非索引列使用isin

In [141]: s = pd.Series(np.arange(5), index=np.arange(5)[::-1], dtype='int64')
In [143]: s.isin([2, 4, 6])
Out[143]: 
4 False
3 False
2  True
1 False
0  True
dtype: bool
In [144]: s[s.isin([2, 4, 6])]
Out[144]: 
2 2
0 4
dtype: int64

索引列使用isin

In [145]: s[s.index.isin([2, 4, 6])]
Out[145]: 
4 0
2 2
dtype: int64
# compare it to the following
In [146]: s[[2, 4, 6]]
Out[146]: 
2 2.0
4 0.0
6 NaN
dtype: float64

结合any()/all()在多列索引时

In [151]: df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'],
 .....:     'ids2': ['a', 'n', 'c', 'n']})
 .....: 
In [156]: values = {'ids': ['a', 'b'], 'ids2': ['a', 'c'], 'vals': [1, 3]}
In [157]: row_mask = df.isin(values).all(1)
In [158]: df[row_mask]
Out[158]: 
 ids ids2 vals
0 a a  1

where()

In [1]: dates = pd.date_range('1/1/2000', periods=8)
In [2]: df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
In [3]: df
Out[3]: 
     A   B   C   D
2000-01-01 0.469112 -0.282863 -1.509059 -1.135632
2000-01-02 1.212112 -0.173215 0.119209 -1.044236
2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
2000-01-04 0.721555 -0.706771 -1.039575 0.271860
2000-01-05 -0.424972 0.567020 0.276232 -1.087401
2000-01-06 -0.673690 0.113648 -1.478427 0.524988
2000-01-07 0.404705 0.577046 -1.715002 -1.039268
2000-01-08 -0.370647 -1.157892 -1.344312 0.844885
In [162]: df.where(df < 0, -df)
Out[162]: 
     A   B   C   D
2000-01-01 -2.104139 -1.309525 -0.485855 -0.245166
2000-01-02 -0.352480 -0.390389 -1.192319 -1.655824
2000-01-03 -0.864883 -0.299674 -0.227870 -0.281059
2000-01-04 -0.846958 -1.222082 -0.600705 -1.233203
2000-01-05 -0.669692 -0.605656 -1.169184 -0.342416
2000-01-06 -0.868584 -0.948458 -2.297780 -0.684718
2000-01-07 -2.670153 -0.114722 -0.168904 -0.048048
2000-01-08 -0.801196 -1.392071 -0.048788 -0.808838

DataFrame.where() differs from numpy.where()的区别

In [172]: df.where(df < 0, -df) == np.where(df < 0, df, -df)

当series对象使用where()时,则返回一个序列

In [141]: s = pd.Series(np.arange(5), index=np.arange(5)[::-1], dtype='int64')
In [159]: s[s > 0]
Out[159]: 
3 1
2 2
1 3
0 4
dtype: int64
In [160]: s.where(s > 0)
Out[160]: 
4 NaN
3 1.0
2 2.0
1 3.0
0 4.0
dtype: float64

抽样筛选

DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)

当在有权重筛选时,未赋值的列权重为0,如果权重和不为1,则将会将每个权重除以总和。random_state可以设置抽样的种子(seed)。axis可是设置列随机抽样。

In [105]: df2 = pd.DataFrame({'col1':[9,8,7,6], 'weight_column':[0.5, 0.4, 0.1, 0]})
In [106]: df2.sample(n = 3, weights = 'weight_column')
Out[106]: 
 col1 weight_column
1  8   0.4
0  9   0.5
2  7   0.1

增加行

df.loc[3,:]=4
  a b c
0 1.0 a A
1 2.0 b B
2 3.0 c C
3 4.0 4 4

插入行

pandas里并没有直接指定索引的插入行的方法,所以要自己设置

line = pd.DataFrame({df.columns[0]:"--",df.columns[1]:"--",df.columns[2]:"--"},index=[1])
df = pd.concat([df.loc[:0],line,df.loc[1:]]).reset_index(drop=True)#df.loc[:0]这里不能写成df.loc[0],因为df.loc[0]返回的是series
  a b c
0 1.0 a A
1 -- -- --
2 2.0 b B
3 3.0 c C
4 4.0 4 4

交换行

df.loc[[1,2],:]=df.loc[[2,1],:].values
 a b c
0 1 a A
1 3 c C
2 2 b B

删除行

df.drop(0,axis=0,inplace=True)
print(df)
 a b c
1 2 b B
2 3 c C

注意

在以时间作为索引的数据框中,索引是以整形的方式来的。

In [39]: dfl = pd.DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=pd.date_range('20130101',periods=5))
In [40]: dfl
Out[40]: 
     A   B   C   D
2013-01-01 1.075770 -0.109050 1.643563 -1.469388
2013-01-02 0.357021 -0.674600 -1.776904 -0.968914
2013-01-03 -1.294524 0.413738 0.276662 -0.472035
2013-01-04 -0.013960 -0.362543 -0.006154 -0.923061
2013-01-05 0.895717 0.805244 -1.206412 2.565646
In [41]: dfl.loc['20130102':'20130104']
Out[41]: 
     A   B   C   D
2013-01-02 0.357021 -0.674600 -1.776904 -0.968914
2013-01-03 -1.294524 0.413738 0.276662 -0.472035
2013-01-04 -0.013960 -0.362543 -0.006154 -0.923061

列操作

选择某一列

print(df.loc[:,"a"])
0 1
1 2
2 3
Name: a, dtype: int64

选择多列

print(df.loc[:,"a":"b"])
 a b
0 1 a
1 2 b
2 3 c

增加列,如果对已有的列,则是赋值

df.loc[:,"d"]=4
 a b c d
0 1 a A 4
1 2 b B 4
2 3 c C 4

交换两列的值

df.loc[:,['b', 'a']] = df.loc[:,['a', 'b']].values
print(df)
 a b c
0 a 1 A
1 b 2 B
2 c 3 C

删除列

1)直接del DF[‘column-name']

2)采用drop方法,有下面三种等价的表达式:

DF= DF.drop(‘column_name', 1);

DF.drop(‘column_name',axis=1, inplace=True)

DF.drop([DF.columns[[0,1,]]], axis=1,inplace=True)

df.drop("a",axis=1,inplace=True)
print(df)
 b c
0 a A
1 b B
2 c C

还有一些其他的功能:

切片df.loc[::,::]

选择随机抽样df.sample()

去重.duplicated()

查询.lookup

以上这篇Pandas 数据框增、删、改、查、去重、抽样基本操作方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
django自定义Field实现一个字段存储以逗号分隔的字符串
Apr 27 Python
Django中对数据查询结果进行排序的方法
Jul 17 Python
Python打包文件夹的方法小结(zip,tar,tar.gz等)
Sep 18 Python
Python中存取文件的4种不同操作
Jul 02 Python
python 使用正则表达式按照多个空格分割字符的实例
Dec 20 Python
django与小程序实现登录验证功能的示例代码
Feb 19 Python
Python利用WMI实现ping命令的例子
Aug 14 Python
Anaconda+Pycharm环境下的PyTorch配置方法
Mar 13 Python
Python selenium爬取微信公众号文章代码详解
Aug 12 Python
anaconda3安装及jupyter环境配置全教程
Aug 24 Python
Python爬虫Scrapy框架CrawlSpider原理及使用案例
Nov 20 Python
pytorch 权重weight 与 梯度grad 可视化操作
Jun 05 Python
dataframe设置两个条件取值的实例
Apr 12 #Python
使用python编写监听端
Apr 12 #Python
Python实现针对给定单链表删除指定节点的方法
Apr 12 #Python
pandas系列之DataFrame 行列数据筛选实例
Apr 12 #Python
python:pandas合并csv文件的方法(图书数据集成)
Apr 12 #Python
用pandas按列合并两个文件的实例
Apr 12 #Python
Python中多个数组行合并及列合并的方法总结
Apr 12 #Python
You might like
php初学者写及时补给skype用户充话费的小程序
2008/11/02 PHP
php实现登录tplink WR882N获取IP和重启的方法
2016/07/20 PHP
laravel实现批量更新多条记录的方法示例
2017/10/22 PHP
php实现解析xml并生成sql语句的方法
2018/02/03 PHP
php高清晰度无损图片压缩功能的实现代码
2018/12/09 PHP
PHP通过文件保存和更新信息的方法分析
2019/09/12 PHP
新浪刚打开页面出来的全屏广告代码
2007/04/02 Javascript
Extjs学习过程中新手容易碰到的低级错误积累
2010/02/11 Javascript
JavaScript学习历程和心得小结
2010/08/16 Javascript
jquery.simple.tree插件 更简单,兼容性更好的无限树插件
2010/09/03 Javascript
jquery blockUI 遮罩不能消失与不能提交的解决方法
2011/09/17 Javascript
JavaScript字符串对象substr方法入门实例(用于截取字符串)
2014/10/16 Javascript
详解Javascript动态操作CSS
2014/12/08 Javascript
javascript中的Base64、UTF8编码与解码详解
2015/03/18 Javascript
基于javascript实现单选及多选的向右和向左移动实例
2015/07/25 Javascript
JS操作JSON方法总结(推荐)
2016/06/14 Javascript
jQuery Mobile和HTML5开发App推广注册页
2016/11/07 Javascript
jQuery实现web页面樱花坠落的特效
2017/06/01 jQuery
[02:03]《现实生活中的DOTA2》—林书豪&DOTA2职业选手出演短片
2015/08/18 DOTA
用生成器来改写直接返回列表的函数方法
2017/05/25 Python
python中找出numpy array数组的最值及其索引方法
2018/04/17 Python
Python分割指定页数的pdf文件方法
2018/10/26 Python
python输出pdf文档的实例
2020/02/13 Python
python opencv把一张图片嵌入(叠加)到另一张图片上的实现代码
2020/06/11 Python
Python Merge函数原理及用法解析
2020/09/16 Python
美国零售商店:Blue&Cream
2017/04/07 全球购物
英国老牌潮鞋店:Offspring
2019/08/19 全球购物
AURALog面试题软件测试方面
2013/10/22 面试题
理货员的岗位职责
2013/11/23 职场文书
手机被没收检讨书
2014/02/22 职场文书
小学清明节活动总结
2014/07/04 职场文书
基层党组织建设整改方案
2014/09/16 职场文书
社区党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
小学运动会报道稿
2014/10/04 职场文书
培训通知
2015/04/17 职场文书
母亲去世追悼词
2015/06/23 职场文书