生信数据分析高效Python代码

1. Pandas + glob获取指定目录下的文件列表

python 复制代码
import pandas as pd
import glob

data_dir = "/public/data/"
# 获取文件后缀为.txt的文件列表
df_all = pd.concat([pd.read_csv(f, sep='\t') for f in glob.glob(data_dir + '*.txt')])
print(df_all)

2. 使用 enumerate 函数获取索引和值

python 复制代码
# A-K 字母列表
letter = [chr(ord('A') + i) for i in range(0, 11)]

# 输出索引和值
for idx, value in enumerate(letter):
    print(f"{idx}\t{value}")

3. 使用 zip 函数同时遍历多个列表

python 复制代码
# 0-10 数字列表
number = [n for n in range(0, 11)]
# A-K 字母列表
letter = [chr(ord('A') + i) for i in range(0, 11)]

for number, letter in zip(letter, number):
    print(f"{letter}: {number}")
    
# 0: A
# 1: B
# 2: C
# 3: D
# 4: E
# 5: F
# 6: G
# 7: H
# 8: I
# 9: J
# 10: K

4. 内置函数map + filter 过滤数据

python 复制代码
number = [n for n in range(0, 11)]

# 获取平方数
squared_numbers = list(map(lambda x: x**2, number)
print(squared_numbers) 
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 获取偶数
even_numbers = list(filter(lambda x: x % 2 == 0, number))
print(even_numbers)
# [0, 2, 4, 6, 8, 10]

5. 使用concurrent.futures模块实现循环的并发处理,提高计算效率

python 复制代码
import concurrent.futures
def square(num):
    return num ** 2

with concurrent.futures.ThreadPoolExecutor() as executor:
    res = list(executor.map(square, number))
    
print(res)

6. 使用asyncio模块实现异步处理,提高并发性能

python 复制代码
import asyncio
import math
async def sqrt(num):
    return math.sqrt(num)

async def calculate():
    run_tasks = [sqrt(num) for num in number]
    
    results = await asyncio.gather(*run_tasks)
    print(results)

asyncio.run(calculate())

7. 程序运行分析装饰器

python 复制代码
import time

def analysis_time(func):
    def warpper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, *kwargs)
        end_time = time.time()
        print(f"{func.__name__} program run time: {end_time - start_time}s")
        return res
    return warpper

# 并行计算
import concurrent.futures
def square(num):
    return num ** 2
    
@analysis_time
def calulate(number):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        res = list(executor.map(square, number))
        return res

print(calulate(number))
# calulate program run time: 0.002947568893432617s
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
相关推荐
java1234_小锋2 分钟前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 计算图和 tf.function 简介
python·深度学习·tensorflow·tensorflow2
程序员晚枫5 分钟前
Python 3.14新特性:Zstandard压缩库正式加入标准库,性能提升30%
python
逆境清醒9 分钟前
VS Code配置Python开发环境系列(1)___VScode的安装 ,VScode常用快捷键
vscode·python·visual studio code
珹洺10 分钟前
Java-Spring入门指南(二十一)Thymeleaf 视图解析器
java·开发语言·spring
Predestination王瀞潞14 分钟前
类的多态(Num020)
开发语言·c++
Predestination王瀞潞14 分钟前
类的继承(Num019)
开发语言·c++
万粉变现经纪人32 分钟前
如何解决 pip install -r requirements.txt 无效可编辑项 ‘e .‘(-e 拼写错误)问题
开发语言·python·r语言·beautifulsoup·pandas·pip·scipy
say_fall1 小时前
精通C语言(2.结构体)(内含彩虹)
c语言·开发语言·windows
潇凝子潇1 小时前
在使用Nacos作为注册中心和配置中心时,如何解决服务发现延迟或配置更新不及时的问题
开发语言·python·服务发现
烛阴1 小时前
Python 列表推导式:让你的代码更优雅、更高效
前端·python