【问题标题】:Select specific values from pandas column and sum them从 pandas 列中选择特定值并将它们相加
【发布时间】:2022-01-27 23:02:41
【问题描述】:

我在带有格式列的 csv 文件中也有 8 个人口: pop

我正在尝试使用此代码仅提取 AD 和 DP 值:

import io
import os
import pandas as pd


def read_vcf(path1):
    with open(path1, 'r') as f:
            lines = [l for l in f if not l.startswith('##')]
    return pd.read_csv(
        io.StringIO(''.join(lines)),
        dtype={'#CHROM': str, 'POS': int, 'ID': str, 'REF': str, 'ALT': str,
               'QUAL': str, 'FILTER': str, 'INFO': str},
        sep='\t'
    ).rename(columns={'#CHROM': 'CHROM'})


def extract_AD(info):
    AD= int((info.split(':')[1]).split(',')[0])
    return AD

path1 = "C://Users//USER//Desktop//Anas/VCFs_1/test_1.vcf"

file =read_vcf(path1)


pop1 = file[["FORMAT","NEN_001","NEN_003","NEN_200","NEN_300","LAB_004","LAB_300","LAB_400","LAB_500"]]

cols_to_apply = ["NEN_001","NEN_003","NEN_200","NEN_300","LAB_004","LAB_300","LAB_400","LAB_500"]

tst1pop1 = pd.DataFrame(pop1)
AD= tst1pop1[cols_to_apply].applymap(extract_AD)
#AD= pop1["NEN_001"].apply(extract_AD)


def extract_DP(info):
    DP = info.split(':')[2:3]
    return DP

print("AD Values:"+"\n",AD)


DP= tst1pop1[cols_to_apply].applymap(extract_DP)
print("DP Values:\n",DP)


Sum1 = AD.sum(axis=1)
print(Sum1)
SumAD = sum(Sum1)
print(SumAD)

但它给了我列表中的 DP 值,所以我无法对它们求和

输出: Output

如何从列表中获取整数的 dp 值,以便按行求和?

【问题讨论】:

    标签: python bioinformatics


    【解决方案1】:

    这应该做吗? :How to remove square bracket from pandas dataframe

    df['value'] = df['value'].str[0]
    

    【讨论】:

    • 我正在尝试这个:DP= tst1pop1[cols_to_apply].applymap(extract_DP) DP1 = DP[["NEN_001","NEN_003","NEN_200","NEN_300","LAB_004"," LAB_300","LAB_400","LAB_500"]].str[0] print("DP Values:\n",DP1) 但它告诉我错误:Dataframe 对象没有属性 str
    • 是的,该方法可能仅适用于列,即系列。又快又脏:对于 DP 中的列:DP[column] = DP[column].str[0]
    • 如何从多列中提取值?
    【解决方案2】:

    如果您想编辑 DP 的所有列,一个简单的解决方法是遍历列并更改如下值:

    DP= tst1pop1[cols_to_apply].applymap(extract_DP)
    
    for column in DP: 
        DP[column] = DP[column].str[0].astype(int)
    
    print("DP Values:\n",DP)
    

    【讨论】:

    • 我正在尝试:DP= tst1pop1[cols_to_apply].applymap(extract_DP) 用于 DP 中的列:DP[column] = DP[column].str[0] print("DP 值:\n ",DP) Sum2 = DP.sum(axis=1) print("Total DP Sum:",Sum2) 但它给我的所有总和都是 0?
    • 也许您需要转换为 int,如我的编辑所示?
    • 当我尝试将它们转换为 int 时,它显示另一个错误:ValueError: cannot convert float NaN to integer
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 2019-12-02
    • 1970-01-01
    • 2014-06-03
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    相关资源
    最近更新 更多