python数据分析进阶

python学习笔记



前言

#生信100天打卡系列


pandas 入门

[2/100]pandas 数据读取

  1. pd.read_csv(path, sep = “\t”, header = None, names = [‘pdate’, ‘pv’, ‘uv’])
  2. pd.read_excel
  3. pd.read_sql
import pandas as pd
import numpy as np
name = pd.read_csv("../name_id.xls", sep = "\t", names = ['sample', 'subpopulation'])
name

pandas 的数据结构

  • dataframe --> 二维数据、整个表格、 多行多列
  • series --> 一维数据、一行一列(类似于字典, 比较好处理)
    • series 由一组数据(不同的数据类型)以及与之相关索引构成

Series

仅有数据列表即可产生简单的Series
s1 = pd.Series([1, 'a', 5.2, 7])
s1
0      1
1      a
2    5.2
3      7
dtype: object
s1.index
RangeIndex(start=0, stop=4, step=1)
s1.values
array([1, 'a', 5.2, 7], dtype=object)
在创建Series时指定索引
s2 = pd.Series([1, 'a', 5.2, 7], index = ['a', 'b', 'd', 'e'])
s2
a      1
b      a
d    5.2
e      7
dtype: object
使用字典创建Series
  • 字典的keys为索引, values为值
sdata = {'Ohio' : 35000, 'Texas' : 72000, 'Oregon' : 16000, 'Utah' : 5000}
s3 = pd.Series(sdata)
s3
Ohio      35000
Texas     72000
Oregon    16000
Utah       5000
dtype: int64
根据标签索引查询数据
  • 类似字典dict
  • 查询一个值, 返回的是这个值本身
  • 同时查询多个值, 返回的是一个Series
s2
a      1
b      a
d    5.2
e      7
dtype: object
s2['a']
1
type(s2['a'])
int
s2[['b', 'a']]
b    a
a    1
dtype: object
type(s2[['b', 'a']])
pandas.core.series.Series

dataframe

  • 每列可以是不同的类型
  • 既有行索引index, 也有列索引columns
  • 也可以被看做是由Series组成的字典
# 根据多个字典序列创建dataframe
data = {
    'state' : ['Ohio', 'Utah', 'Ohio', 'Texas', 'Ohio'],
    'year' : [2000, 2001, 2002, 2003, 2004],
    'pop' : [1.5, 1.7, 3.6, 2.4, 2.9]
}
df = pd.DataFrame(data)
df
stateyearpop
0Ohio20001.5
1Utah20011.7
2Ohio20023.6
3Texas20032.4
4Ohio20042.9
dataframe 查询
  • 查询一行, 结果是一个Series
  • 查询多行, 结果是一个Dataframe
# 查询一行
df.loc[1]
state    Utah
year     2001
pop       1.7
Name: 1, dtype: object
# 查询多行
df.loc[1:3]
stateyearpop
1Utah20011.7
2Ohio20023.6
3Texas20032.4
type(df.loc[1:3])
pandas.core.frame.DataFrame

[2/100]pandas 数据查询

  1. df.loc , 根据行、列的标签值查询
  2. df.iloc , 根据行、列的数字位置查询
  3. df.where
  4. df.query
  • .loc 既能查询, 又能覆盖写入

使用df.loc进行数据查询

  • 使用单个label值进行查询
  • 使用值列表批量查询
  • 使用数值区间进行范围查询
  • 使用条件表达式查询
  • 调用函数查询
读取数据
na = pd.read_table("../name_id.xls", header = None, names = ['samples', 'subpopulation'])
na
samplessubpopulation
0110CA
1111CA
2113CA
3117CA
119MPSM10MP
120MPSM11MP
121MPSM12MP
122MPSM13MP
155553WA
156660WA
157855WA
250P14OG
251P28OG
# 设定索引为samples
na.set_index('samples', inplace = True)
na.index
Index(['110', '111', '113', '117', '120', '124', '128', '129', '130', '142',
       ...
       'P64', 'P65', 'P67', 'P70', 'P7', 'P81', 'P84', 'P8', 'P14', 'P28'],
      dtype='object', name='samples', length=252)
na
# 将subpopulation列中的CA替换为test
na.loc[:, "subpopulation"] = na["subpopulation"].str.replace("CA", "test").astype('str')
na.head()
subpopulation
samples
110test
111test
113test
117test
120test
查询单个值
na
使用值列表进行查询
na.loc[['110', '117'], 'subpopulation']
samples
110    CA
117    CA
Name: subpopulation, dtype: object
使用数值区间进行范围查询
na.loc['110':'117', 'subpopulation']
samples
110    CA
111    CA
113    CA
117    CA
Name: subpopulation, dtype: object
使用iloc数字索引进行查询
na.iloc[1:20, 0]
samples
111    CA
113    CA
117    CA
120    CA
124    CA
128    CA
129    CA
130    CA
142    CA
143    CA
147    CA
153    CA
161    CA
162    CA
170    CA
171    CA
172    CA
188    CA
194    CA
Name: subpopulation, dtype: object
使用条件表达式进行查询
na[na.loc[:,'subpopulation'] == 'CA']
调用函数查询
na.loc[lambda na : (na['subpopulation'] == "CA") | (na['subpopulation'] == "OG"), :]
subpopulation
samples
110CA
111CA
P14OG
P28OG

[3/100]pandas 新增数据列

  1. 直接赋值
  2. df.apply
  3. df.assign
  4. 按条件选择分组分别赋值
import numpy as np
import pandas as pd

读取数据

df = pd.read_table('../name_id.xls', sep = '\t', header = None, names = ['samples', 'subpopulation'])
df.head()
samplessubpopulation
0110CA
1111CA
2113CA
3117CA
4120CA
df.set_index('samples', inplace = True)
df.head()
subpopulation
samples
110CA
111CA
113CA
117CA
120CA

直接赋值

df.loc[:, 'order'] = [int(i) for i in range(1,253)]
df
subpopulationorder
samples
110CA1
111CA2
113CA3
117CA4
120CA5
.........
P81WA248
P84WA249
P8WA250
P14OG251
P28OG252

252 rows × 2 columns

df.apply方法

  • Apply a function along an axis of the DataFrame
  • Objects passed to the function are Series objects whose index is either the DataFrame’s index(axis=0)
  • or the DataFrame’s columns(axis = 1)
  • 实例:添加一列中文注释:
    1. 如果为CA,则注释为栽培薄皮
    2. 如果为WA,则注释为野生薄皮
    3. 如果为MP,则注释为马泡
    4. 如果为OG,则注释为外群
def add_column(x):
    if x['subpopulation'] == 'CA':
        return "栽培薄皮"
    elif x['subpopulation'] == 'WA':
        return "野生薄皮"
    elif x['subpopulation'] == 'MP':
        return "马泡"
    else:
        return "外群"
df.loc[:, 'un'] = df.apply(add_column, axis = 1)
df
subpopulationorderun
samples
110CA1栽培薄皮
111CA2栽培薄皮
113CA3栽培薄皮
117CA4栽培薄皮
120CA5栽培薄皮
............
P81WA248野生薄皮
P84WA249野生薄皮
P8WA250野生薄皮
P14OG251外群
P28OG252外群

252 rows × 3 columns

查看un的计数
  • df[‘un’].value_counts()
df['un'].value_counts()
栽培薄皮    119
野生薄皮     95
马泡       36
外群        2
Name: un, dtype: int64

df.assign方法

  • Assign new columns to a Dataframe
  • Return a new object with all original columns in addition to new ones.
  • 不会修改Dataframe本身,返回的是一个新的对象
# 可以同时新增多个列
df.assign(
    sort = lambda x : x['order'],
    sort1 = lambda x : x['order'] * 2
)
subpopulationorderunsortsort1
samples
110CA1栽培薄皮12
111CA2栽培薄皮24
113CA3栽培薄皮36
117CA4栽培薄皮48
120CA5栽培薄皮510
..................
P81WA248野生薄皮248496
P84WA249野生薄皮249498
P8WA250野生薄皮250500
P14OG251外群251502
P28OG252外群252504

252 rows × 5 columns

按条件选择分组分别赋值

  • 按条件优先选择数据,然后对这部分数据赋值新列
# 创建一个空列(一种创建新列的方法)
# 用到了broadcast机制
df['priority'] = ''
df.loc[df['order'] <= 30, 'priority'] = "第一组"
df.loc[df['order'] > 30, 'priority'] = "第二组"
df
subpopulationorderunpriority
samples
110CA1栽培薄皮第一组
111CA2栽培薄皮第一组
113CA3栽培薄皮第一组
117CA4栽培薄皮第一组
120CA5栽培薄皮第一组
...............
P81WA248野生薄皮第二组
P84WA249野生薄皮第二组
P8WA250野生薄皮第二组
P14OG251外群第二组
P28OG252外群第二组

252 rows × 4 columns

df['priority'].value_counts()
第二组    222
第一组     30
Name: priority, dtype: int64

[4/100]pandas 数据统计函数

  1. 汇总类统计
  2. 唯一去重和按值计数
  3. 相关系数和方差
import pandas as pd
sample = pd.read_table('../name_id.xls', header = None, sep = '\t', names = ['samples', 'subpopulation'])
sample.head()
samplessubpopulation
0110CA
1111CA
2113CA
3117CA
4120CA
sample.set_index('samples', inplace = True)
sample.head(10)
subpopulation
samples
110CA
111CA
113CA
117CA
120CA
124CA
128CA
129CA
130CA
142CA
sample['order'] = [int(i) for i in range(1,253)]
sample.head(10)
subpopulationorder
samples
110CA1
111CA2
113CA3
117CA4
120CA5
124CA6
128CA7
129CA8
130CA9
142CA10
sample = sample.assign(
    sort = sample['order'],
    sort1 = sample['order'] * 2
)
sample
subpopulationordersortsort1
samples
110CA112
111CA224
113CA336
117CA448
120CA5510
...............
P81WA248248496
P84WA249249498
P8WA250250500
P14OG251251502
P28OG252252504

252 rows × 4 columns

sample['priority'] = ''
sample.loc[sample['order'] <= 30, 'priority'] = "first group"
sample.loc[sample['order'] > 30, 'priority'] = 'second group'
sample
subpopulationordersortsort1priority
samples
110CA112first group
111CA224first group
113CA336first group
117CA448first group
120CA5510first group
..................
P81WA248248496second group
P84WA249249498second group
P8WA250250500second group
P14OG251251502second group
P28OG252252504second group

252 rows × 5 columns

汇总类统计

# 一次提取所有数字列的统计结果
sample.describe()
ordersortsort1
count252.000000252.000000252.000000
mean126.500000126.500000253.000000
std72.89032972.890329145.780657
min1.0000001.0000002.000000
25%63.75000063.750000127.500000
50%126.500000126.500000253.000000
75%189.250000189.250000378.500000
max252.000000252.000000504.000000
# 查看单个列
display(sample['order'].mean())
display(sample['order'].max())
display(sample['order'].min())
126.5

252

1

唯一去重和按值计数

唯一性去重
sample['priority'].unique()
array(['first group', 'second group'], dtype=object)
按值计数
sample['priority'].value_counts()
second group    222
first group      30
Name: priority, dtype: int64

相关系数和协方差

  • 协方差:衡量同向反向程度, 如果协方差为正, 说明X、Y同向变化, 协方差越大说明同向程度越高; 如果协方差为负, 说明X、Y反向运动, 想方差越小说明反向程度越高
  • 相关系数: 衡量相似度程度, 当他们的相关系数为1时, 说明两个变量变化时的正向相似度最大, 当相关系数为 -1 时, 说明两个变量变化的反向相似度最大
# 协方差
sample.cov()
ordersortsort1
order5313.05313.010626.0
sort5313.05313.010626.0
sort110626.010626.021252.0
# 相关系数
sample.corr()
ordersortsort1
order1.01.01.0
sort1.01.01.0
sort11.01.01.0
# 查看单个
display(sample['order'].cov(sample['sort']))
display(sample['order'].corr(sample['sort1']))
display(sample['order'].corr(sample['sort1'] - sample['sort']))
5313.0

1.0

1.0

[4/100]pandas 缺失值的处理

  • pandas使用以下函数处理缺失值:
    • isnull 和 notnull : 检查是否是空值, 可用于df和series
    • dropna : 丢弃、删除缺失值
      • axis : 删除行还是列, 0 for index ,1 for columns, default is 0
      • how : 如果等于any则任何值为空都删除, 如果等于all则所有值为空才删除
      • inplace : 如果为True则修改当前的df, False则返回新的df
    • fillna :填充空值
      • value : 要填充的值, 可以是单个值, 也可以是字典(key是列名,value是值)
      • method : 等于 ffill 使用前一个不为空的值来填充, 等于 bfill 使用后一个不为空的值来填充
      • axis : 按行还是列填充
      • inplace : 返回的对象

读取excel

import openpyxl
df = pd.read_excel('../pd_test.xlsx', skiprows = 0)
df
姓名科目分数
0小明语文NaN
1NaN数学80.0
2NaN英语90.0
3NaNNaNNaN
4小王语文85.0
5NaN数学NaN
6NaN英语90.0
7NaNNaNNaN
8小刚语文85.0
9NaN数学80.0
10NaN英语NaN

检查空值

df.isnull()
姓名科目分数
0FalseFalseTrue
1TrueFalseFalse
2TrueFalseFalse
3TrueTrueTrue
4FalseFalseFalse
5TrueFalseTrue
6TrueFalseFalse
7TrueTrueTrue
8FalseFalseFalse
9TrueFalseFalse
10TrueFalseTrue
df['分数'].isnull()
0      True
1     False
2     False
3      True
4     False
5      True
6     False
7      True
8     False
9     False
10     True
Name: 分数, dtype: bool
# 筛选没有空分数的所有行
df.loc[df['分数'].notnull() , :]
姓名科目分数
1NaN数学80.0
2NaN英语90.0
4小王语文85.0
6NaN英语90.0
8小刚语文85.0
9NaN数学80.0

删除掉全是空值的列

df.dropna(axis = 'columns', how = 'all', inplace = True)
df
姓名科目分数
0小明语文NaN
1NaN数学80.0
2NaN英语90.0
3NaNNaNNaN
4小王语文85.0
5NaN数学NaN
6NaN英语90.0
7NaNNaNNaN
8小刚语文85.0
9NaN数学80.0
10NaN英语NaN

删除掉全是空值的行

df.dropna(axis = 'index', how = 'all', inplace = True)
df
姓名科目分数
0小明语文NaN
1NaN数学80.0
2NaN英语90.0
4小王语文85.0
5NaN数学NaN
6NaN英语90.0
8小刚语文85.0
9NaN数学80.0
10NaN英语NaN

将分数列的空值填充为0

df['分数'].fillna(0, inplace = True)
df
姓名科目分数
0小明语文0.0
1NaN数学80.0
2NaN英语90.0
4小王语文85.0
5NaN数学0.0
6NaN英语90.0
8小刚语文85.0
9NaN数学80.0
10NaN英语0.0
# 另一种方法
df.fillna({'分数' : 0}, inplace = True)
df
姓名科目分数
0小明语文0.0
1NaN数学80.0
2NaN英语90.0
4小王语文85.0
5NaN数学0.0
6NaN英语90.0
8小刚语文85.0
9NaN数学80.0
10NaN英语0.0

对姓名列的缺失值进行填充

df['姓名'].fillna(method = 'ffill', inplace = True)
df
姓名科目分数
0小明语文0.0
1小明数学80.0
2小明英语90.0
4小王语文85.0
5小王数学0.0
6小王英语90.0
8小刚语文85.0
9小刚数学80.0
10小刚英语0.0

将清洗好的excel保存

df.to_excel('../pd_test_clean.xlsx', index = False)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值