Skip to main content
 首页 » 编程设计

python之如何获取 pandas 数据框中不唯一且按行排列的项目数

2025年05月04日9yjmyzz

我发现的大多数解决方案都是获取数据框中唯一项目(我不想要)的数量,或者按具有清晰标题的列进行计数。

我的数据框如下所示:

       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) 

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

请您参考如下方法:

使用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