​python单细胞学习笔记-day4(续)

学术   2025-01-20 17:32   黑龙江  

前面,我们生信技能树的讲师小洁老师与萌老师新开了一个学习班:《掌握Python,解锁单细胞数据的无限可能》,身为技能树的一员,近水楼台先得月,学起!下面是我的学习笔记,希望可以给你带来一点参考

前面几天的学习笔记:

今天继续学习视频:python_day4 !一口气学完吧!

touch day4.ipynb

课前复习到 37:39

1、条件语句

  • if 语句:if不支持直接批量计算,逻辑值只能是一个
  • if else语句

试试看报错的:

# 这段代码会报错
import numpy as np

y = np.array([3,5,-1,0])
print(y > 0)
y.any()

if(y>0):
 print("pos")
else:
 print("neg")

1.1 np.where

python里面的numpy提供了np.where函数,支持数组运算

import numpy as np # type: ignore

y = np.array([3,5,-1,0])
y2 = np.where(y>0"pos""neg")
print(y2.tolist())

1.2 case_when

pandas 里面的 case_when 方法支持多个条件

import pandas as pd

y = pd.Series([3,5,-1,0])
y.case_when([
 (y > 0"pos"),
 (y < 0"neg"),
 (pd.Series(True), "0")
])

2、循环语句

python里面的循环使用for函数

z = range(1,6)
for i in z:
 print(i)

ps = ["a","b","c"]
for p in ps:
 print(p)

3、列表推导式 55:57

相比传统的for循环,列表推导式更加简洁和易读,可以把结果直接保存为列表或者是字典

3.1 列表推导式

# 列表推导式
numbers = [1,2,3,4,5]
# 计算平方
[x**2 for x in numbers]

3.2 字典推到式

# 字典推导式
{x: x**2 for x in numbers}

4、批量读取文件

day3_preview文件夹中有四个文件:

import os
os.listdir("day3_preview")

from glob import glob
import pandas as pd

# 搜索所有以 csv 结尾的文件
files = glob("day3_preview/*.csv")
files

# 删除一个
# files.pop()
files.remove('day3_preview/gene.csv')
files

# 读取
result = []
for i in range(len(files)):
 result.append(pd.read_csv(files[i]))

# 使用 pd.concat 将文件按照行拼接在一起
res = pd.concat(result, ignore_index=True)
res.head()

列表推导式读取:

result = [pd.read_csv(x) for x in files]
print([x.shape for x in result])
re = pd.concat(result, ignore_index=True)
print(re.shape)
re.head()

day3课后习题讲解 01:37:04

1.列表排序

  • 创建一个包含任意5个整数的列表
  • 使用.sort()方法将其从小到大排序
  • 使用.sort()方法将其从大到小排序
import random

# 创建一个包含5个随机整数的列表,假设我们想要的范围是1到100
my_random = [random.randint(1100for _ in range(5)]
my_random

# 从小到大排序
my_random.sort()
my_random

# 从大到小排序
my_random.sort(reverse=True)
my_random

2.去重和计数

  • 以别名np导入numpy
  • 创建由a,b,c,a,b,d组成的列表,赋值给a
  • 去重,并输出去重后的结果
  • 去重,并统计每个数值出现的次数
import numpy as np

a = ['a','b','c','a','b','d']
print(a)

# 去重
print(np.unique(a))

# 去重并计数
uniq,counts=np.unique(a,return_counts=True)
print(uniq)
print(counts)
  • 以别名pd导入pandas
  • 创建由a,b,c,a,b,d组成的列表,赋值给a
  • 去重,并输出去重后的结果
  • 去重,并统计每个数值出现的次数
import pandas as pd
a = ['a','b','c','a','b','d']
print(a)
b = pd.Series(a)
print(b)

uniq_a = b.unique()
count_a = b.value_counts()
print(uniq_a)
print(count_a)

3.矩阵

  • 新建矩阵,赋值给m1
  • 输出第二列的所有元素
import numpy as np

m1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(m1[:,1])
  • 使用切片操作提取该矩阵的前两行和后两列
print(m1)
sub_m = m1[0:2,1:3]
print(sub_m)

4.数据框

数据框如下:

import pandas as pd

df1 = pd.DataFrame({
 'gene': ['gene' + str(i) for i in range(1,5)],
 'change': ['up','up','down','down'],
 'score': [5,3,-1,-3]
})
df1

以下代码错误的是:

A、df1.gene

B、df1[['gene','change']]

C、df1[0,1]:正确的为 df1.iloc[0,1]

D、df1.shape

计算score列的最小值的正确代码是:A、B

A、df1.score.min()

B、min(df1.score)

C、min(df1$score)

D、df1$score.min()

绘图工具 seaborn模块 01:53:15

python的绘图工具有:

  • 作图:matplotlib、seaborn、plotnine
  • 拼图:subplots、patchworklib
  • 导出:savefig、ggsave

现在开始学习绘图工具seaborn了,首先在环境中安装一下:

# bash终端
# 安装模块
conda activate sc
pip install seaborn -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
pip install pypalettes -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

seaborn和matplotlib

关系:

  • Seaborn是基于Matplotlib的统计数据可视化库
  • Seaborn是Matplotlib的高级封装
  • Seaborn可以直接使用Matplotlib的方法

优缺点:

  • Matplotlib提供底层绘图能力,更细粒度的定制选项,代码肿
  • Seaborn提供开箱即用的美观样式,代码简洁,细节调整还是要靠Matplotlib

可以选择 用seaborn画图,matplotlib拼图、保存和调细节

seaborn 绘图

seaborn 是一个很受欢迎的图库,代码简洁,图片好看,但细节调整拼图保存还是matplotlib更胜一层。

  • 点图:scatterplot
  • 箱线图:boxplot
  • 点图+趋势线:regplot
  • 热图:clustermap、heatmap
  • 多图叠加:直接连续写绘图代码
  • 拼图:plt.subplots

0、库的安装和示例数据读取

安装已经在前面安装过了,这里直接读取数据:

import pandas as pd

iris = pd.read_csv('day4/iris.csv')
print(iris.head())

1、点图

import seaborn as sns
import matplotlib.pyplot as plt

sns.scatterplot(x='sepal_length', y='sepal_width',
    hue = 'species', data=iris)
plt.show()

最好的配色库 pypalettes

直接使用palette参数即可。2500+种配色:https://python-graph-gallery.com/color-palette-finder/

import pypalettes
pypalettes.load_cmap('a_palette')

换一个配色:

import pypalettes
import seaborn as sns
import matplotlib.pyplot as plt

sns.scatterplot(x='sepal_length', y='sepal_width',palette='a_palette',
    hue = 'species', data=iris)
plt.show()

2、箱线图

sns.boxplot(x='species', y='sepal_length',data=iris,
   palette='Set2',hue='species')
plt.show()

3、点图+趋势线图

sns.regplot(x='sepal_length', y='sepal_width',data=iris)
plt.show()

4、热图

配色风格:https://seaborn.pydata.org/tutorial/color_palettes.html

data = iris.drop('species',axis=1)
g = sns.clustermap(data, cmap='viridis')
plt.show()

热图:sns.heatmap(data,cmap='coolwarm')

sns.heatmap(data,cmap='coolwarm')

5、多图叠加

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(10,6))
# 小提琴图
sns.violinplot(x='species', y='sepal_length',data=iris, palette='Set2',hue='species',alpha=0.3, legend=False)
# 箱线图
sns.boxplot(x='species', y='sepal_length',data=iris, palette='Set2',hue='species',width=0.3, legend=False)
# 点图
sns.stripplot(x='species', y='sepal_length',data=iris,color='black')

plt.title('Sepal Length Distribution')
plt.show()

6、图片设置(matplotlib)

更改x/y轴标题,图片标题

sns.regplot(x='sepal_length', y='sepal_width', data=iris)
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.title('Sepal Length')

7.拼图(matplotlib)

figureaxes以及以及axis的关系:https://steam.oxxostudio.tw/category/python/example/matplotlib-figure-axes.html

什么是 figure?

figure 表示「画布」,表示 atplotlib 绘制图表的空间,在绘制图表时,要先创建一个画布,才能在加入各种元素,储存或输出图片时,也都是以 figure 为单位进行储存或输出。

什么是 axes?

axes 表示「坐标系统」,如果是二维图表,axes 会包含两个坐标轴 (axis )、如果是三维图表,axes 会包含三个坐标轴(axis),依此类推,在一个 figure 之中,可以设定多个 axes,下图呈现 figure、axes 和 asix 的关系。ax是axes的缩写

这个图类似的在 R语言里面也有:《R绘图系统 第二版》

  • plt.subplots(1,2,figsize = (10,5)):一行两列
fig, (ax1, ax2) = plt.subplots(1,2,figsize = (10,5))
sns.scatterplot(x='sepal_length', y='sepal_width', data=iris,ax=ax1)
sns.boxplot(x='species', y='sepal_length', data=iris,palette='Set2',hue = 'species',ax=ax2)
plt.show()

8.图片保存

使用plt.savefig函数

plt.figure(figsize=(106))
sns.boxplot(x='species', y='sepal_length', data=iris, hue='species', palette='Set2', width=0.3, legend=False)
plt.title('Sepal Length Distribution')
plt.savefig("sns_plot1.png")

9.更多示例

更多示例:https://seaborn.pydata.org/examples/index.html

试一下边际散点图:Scatterplot with marginal ticks

https://seaborn.pydata.org/examples/marginal_ticks.html

加载数据。这里特别慢,采用方法:

去 这里下载到本地:https://github.com/mwaskom/seaborn-data,然后本地加载。

load_dataset包含有三个参数:

  1. name: str,代表数据集名字;
  2. cache: boolean,当为True时,从本地加载数据,反之则从网上下载;
  3. data_home: string,代表本地数据的路径
import seaborn as sns
sns.set_theme(style="white", color_codes=True)

mpg = sns.load_dataset('mpg',data_home='day4/seaborn-data-master/',cache=True)
#mpg = sns.load_dataset("mpg")
print(mpg.head())

绘图:

# Use JointGrid directly to draw a custom plot
g = sns.JointGrid(data=mpg, x="mpg", y="acceleration", space=0, ratio=17)
g.plot_joint(sns.scatterplot, size=mpg["horsepower"], sizes=(30120),
             color="g", alpha=.6, legend=False)
g.plot_marginals(sns.rugplot, height=1, color="g", alpha=.6)

本次学习到这里,day4视频刷完~ 下次见

文末友情宣传:

生信入门&数据挖掘线上直播课2025年1月班

时隔5年,我们的生信技能树VIP学徒继续招生啦

满足你生信分析计算需求的低价解决方案


生信技能树
生物信息学学习资料分析,常见数据格式及公共数据库资料分享。常见分析软件及流程,基因检测及癌症相关动态。
 最新文章