如何按行获取数据帧中非唯一项的计数?

2024-06-26 13:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到的大多数解决方案都是获取数据帧中唯一项(我不想要)的计数,或者按标题清晰的列进行计数

我的数据框如下所示:

       1   2   3   4
ILLU1 ATG --T --- TGG
ILLU2 ATG -CT GGG TGG
ILLU3 ATG TTT AAA TGG
ILLU4 -TG --T --- T-G

我试图得到每一行的计数,其中每一列都有一个完整的3碱基序列。因此,如果单元格中存在“-”,它将是零(包括“---”、“N”、“NN”)

所以我试着输出如下:

ILLU1 2
ILLU2 3
ILLU3 4
ILLU4 0

我试过:

df_new = pd.DataFrame() # to hold the final values
count = 0
for rows in df:
   if not sum(df[rows].str.contains("-")) > 0: # if no hyphen present
       count += 1 # add to final count
   else:
       count = count # does not get included final count
       df_new["Final Count"] = count 

print(df_new)

但我只得到一个没有值的空数据帧


Tags: to数据dfnewifcountrowsfinal
2条回答

使用str.contains

s=(~df.apply(lambda x : x.str.contains('-'))).sum(1)
s
Out[384]: 
ILLU1    2
ILLU2    3
ILLU3    4
ILLU4    0
dtype: int64

您可以使用:

df.apply(lambda x: ['-' not in i for i in x]).sum(1)

或者

df.apply(lambda x: ['-' in i for i in x]).ne(1).sum(1)

输出:

ILLU1    2
ILLU2    3
ILLU3    4
ILLU4    0
dtype: int64

相关问题 更多 >