总括

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

列操作

更改列名

df.columns = df.columns.str.strip() # 把columns当成series看待 
df.columns = df.columns.map(lambda x:x) # 使用map函数 
df.rename(columns={’s’:’c’}, inplace=True)

选择某一列

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 Dataframe增、删、改、查、去重、抽样基本操作的更多相关文章

  1. 好用的SQL TVP~~独家赠送[增-删-改-查]的例子

    以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化.  本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...

  2. iOS FMDB的使用(增,删,改,查,sqlite存取图片)

    iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...

  3. iOS sqlite3 的基本使用(增 删 改 查)

    iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...

  4. django ajax增 删 改 查

    具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...

  5. ADO.NET 增 删 改 查

    ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...

  6. MVC EF 增 删 改 查

    using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...

  7. python基础中的四大天王-增-删-改-查

    列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...

  8. 简单的php数据库操作类代码(增,删,改,查)

    这几天准备重新学习,梳理一下知识体系,同时按照功能模块划分做一些东西.所以.mysql的操作成为第一个要点.我写了一个简单的mysql操作类,实现数据的简单的增删改查功能. 数据库操纵基本流程为: 1 ...

  9. MongoDB增 删 改 查

    增 增加单篇文档 > db.stu.insert({sn:'001', name:'lisi'}) WriteResult({ "nInserted" : 1 }) > ...

  10. Go语言之进阶篇mysql增 删 改 查

    一.mysql操作基本语法 1.创建名称nulige的数据库 CREATE DATABASE nulige DEFAULT CHARSET utf8 COLLATE utf8_general_ci; ...

随机推荐

  1. openstack rpc机制

    一.概述: 在openstack项目中,api的调用规则: 跨项目:如nova调用keystone, glance,cinder等,使用rest api(通过相应的python-XXXclient 库 ...

  2. 【MyBatis】MyBatis之分页

    关于MyBatis的搭建可以参见“MyBatis的配置”,MyBatis是对JDBC底层代码的封装,关于Oracle.MySQL.SqlServer的分页可以查看Oracle.SqlServer.My ...

  3. 在iOS开发的Quartz2D使用中实现图片剪切和截屏功能

    原文  http://www.jb51.net/article/75671.htm 图片剪切一.使用Quartz2D完成图片剪切1.把图片显示在自定义的view中先把图片绘制到view上.按照原始大小 ...

  4. Tensorflow中的run()函数

    1 run()函数存在的意义 run()函数可以让代码变得更加简洁,在搭建神经网络(一)中,经历了数据集准备.前向传播过程设计.损失函数及反向传播过程设计等三个过程,形成计算网络,再通过会话tf.Se ...

  5. Python使用matplotlib模块绘制多条折线图、散点图

    用matplotlib模块 #!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水寒城 功能:折线图.散点图测试 ''' import rando ...

  6. 看MySQL官方文档的示例SQL有感

    [背景] 周末比较闲,我这个人又没有什么爱好,当然了读书除外:前一些天我一个同事说:“你一个dba想去写一本“django”书,合适吗?” 我想也是,一个人不能忘了本,所以MySQL还是要好好的搞一搞 ...

  7. Django form入门详解--2

    调整form的输出格式: 默认情况下form的格式化输出是基本table的样式的.但是django中还是为form提供发别的输出样式 1.默认的table样式输出 <html> <h ...

  8. Fast Algorithm To Find Unique Items in JavaScript Array

    When I had the requirement to remove duplicate items from a very large array, I found out that the c ...

  9. Windows系统创建符号链接文件

    源文件夹:E:\深海 创建新硬链接文件夹:D:\微云同步盘\719179409\4-工作资料\深海   使用快捷键Win + X 打开以下菜单,选择命令提示符(管理员) 敲入以下命令:   创建成功后 ...

  10. memcached(一):linux下memcached安装以及启动

    一. 安装文件 Linux系统安装memcached,首先要先安装libevent库. 下载memcached与libevent的安装文件 http://memcached.org/files/mem ...