文章目录

  • 前言
  • 1、列选择
  • 2、行选择
  • 3、行列选择


前言

最近学习宋俊红大佬《对比excel,轻松学习python数据分析》一书整理的一些笔记,内容脑图如下:

python excel每列不同取值_用户信息


不足之处,多多指正。

常用的数据挑选主要为以下三类:

  • 行选择
  • 列选择
  • 行列选择

上述三种操作在excel中都直接通过鼠标,不做赘述,主要总结python如何通过pandas库来实现上述操作。
在此之前,需要了解关于利用pandas库实现几类索引的知识(以行列选择为例)

  • 普通索引:df.loc[[行索引名][列索引名]]
  • 位置索引:df.iloc[[行号][列号]] 从0开始计
  • 布尔索引:df[行限制][列索引名]]
  • 切片索引: df.ix[切片,[列索引]]

1、列选择

# 读取数据
import pandas as pd 
df = pd.read_excel(r"S:\code\jupyter_notebook\big_date\对比excel学习python\章节5用户信息.xlsx",
                  sheet_name = '重复')
df



编号

客户姓名

唯一识别码

成交时间

0

A1

张通

101

2018-08-08

1

A2

李谷

102

2018-08-09

2

A3

孙凤

103

2018-08-10

3

A3

孙凤

103

2018-08-10

4

A4

赵恒

104

2018-08-11

5

A5

赵恒

104

2018-08-12

# 选中单列 直接df[]
df["唯一识别码"].dtype
dtype('int64')
#选取并列多列
df[["编号","客户姓名"]]



编号

客户姓名

0

A1

张通

1

A2

李谷

2

A3

孙凤

3

A3

孙凤

4

A4

赵恒

5

A5

赵恒

#选取不并列的多列
#df[[列索引名]]或者
df.iloc[:,[1,3]]



客户姓名

成交时间

1

李谷

2018-08-09

2

孙凤

2018-08-10

2、行选择

#单行选择
df.loc[[1]]



编号

客户姓名

唯一识别码

成交时间

1

A2

李谷

102

2018-08-09

#并列多行选择
df.iloc[0:3]



编号

客户姓名

唯一识别码

成交时间

0

A1

张通

101

2018-08-08

1

A2

李谷

102

2018-08-09

2

A3

孙凤

103

2018-08-10

# 不并列多行选择
df.iloc[[1,3]]



编号

客户姓名

唯一识别码

成交时间

1

A2

李谷

102

2018-08-09

3

A3

孙凤

103

2018-08-10

df1 = pd.read_excel(r"S:\code\jupyter_notebook\big_date\对比excel学习python\章节5用户信息.xlsx",
                  sheet_name = '缺失')
#有限制条件的行选择
df1[df1["年龄"]>35]



编号

年龄

性别

注册时间

0

A1

54


2018-08-08

2

A3

47


2018-08-10

3

A4

41


2018-08-11

3、行列选择

#普通索引+普通索引
df.loc[[1,2],["编号","客户姓名"]]



编号

客户姓名

1

A2

李谷

2

A3

孙凤

#位置索引+位置索引
df.iloc[[1,2],[1,3]]



客户姓名

成交时间

1

李谷

2018-08-09

2

孙凤

2018-08-10

df1 = pd.read_excel(r"S:\code\jupyter_notebook\big_date\对比excel学习python\章节5用户信息.xlsx",
                  sheet_name = '缺失')
df1



编号

年龄

性别

注册时间

0

A1

54


2018-08-08

1

A2

16

NaN

2018-08-09

2

A3

47


2018-08-10

3

A4

41


2018-08-11

#布尔索引+普通索引
#df1.iloc[[df1["年龄"]<35]
df1[df1["年龄"]>35][["年龄","性别"]]



年龄

性别

0

54


2

47


3

41


#切片索引+切片索引
df.iloc[0:3,1:3]



客户姓名

唯一识别码

0

张通

101

1

李谷

102

2

孙凤

103

#切片索引+普通索引 语法警告链接:http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
df.ix[0:3,["客户姓名","唯一识别码"]]
D:\Program_for_code\Anaconda\lib\site-packages\ipykernel_launcher.py:2: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated



客户姓名

唯一识别码

0

张通

101

1

李谷

102

2

孙凤

103

3

孙凤

103