首页 > 解决方案 > 对熊猫数据框中的列中的特定值进行排序

问题描述

我有一个数据框,例如:

df =     ID  aa_len                                             aa_seq  \
0  001      45  [M, R, S, R, Y, P, L, L, R, G, E, A, V, A, V, ...   
1  002      45  [M, R, S, R, Y, P, L, L, R, G, E, A, V, A, V, ...   

   mut_position  
0              [-1]  
1  [5, 94, 95, 132]  

“mut_position”可以是 -1 或其他非负数 (2,3,4) 或少数数字的列表。例如,它可以是 -1,如 001。一个列表,如 002 或一个数字 - 例如 4。我需要计算没有 -1 的受试者的数量。

我试图通过与-1进行比较并收集那些不同但它似乎有效的那些......

def count_mutations(df, ref_aa_len):
nomis = -1
mutation = (df['mut_position']) != nomis 
print (mutation)

我得到它对两者都是正确的(忽略 ref_aa_len,稍后会出现)-

0    True
1    True

标签: pandas

解决方案


我认为需要list compehension生成器和布尔值True的总和:

df['non_negative'] = [sum(y != -1 for y in x) for x in df['mut_position']]
print (df)
       mut_position  non_negative
0              [-1]             0
1  [5, 94, 95, 132]             4

如果可能的话,还有标量:

print (df)
    mut_position
0           [-1]
1  [5,94,95,132]
2              6
3             -1

df['non_negative'] = [sum(y != -1 for y in x)  
                     if isinstance(x, list) 
                     else int(x != -1) for x in df['mut_position']]
print (df)
       mut_position  non_negative
0              [-1]             0
1  [5, 94, 95, 132]             4
2                 6             1
3                -1             0

如果需要检查第一个值是否列出-1并过滤boolean indexing

df = pd.DataFrame({'mut_position':[[-1], [5,94,95,132],[2,-1], [-1]]})

print (df)
       mut_position
0              [-1]
1  [5, 94, 95, 132]
2           [2, -1]
3              [-1]

df1 = df[df['mut_position'].str[0] != -1 ]
print (df1)
       mut_position
1  [5, 94, 95, 132]
2           [2, -1]

详情

str[0]为选择字符串的第一个字符或可迭代的第一个值工作:

 print (df['mut_position'].str[0])
0   -1
1    5
2    2
3   -1
Name: mut_position, dtype: int64   

并检查-1任何位置使用all

df1 = df[[all(y != -1 for y in x) for x in df['mut_position']]]
print (df1)
       mut_position
1  [5, 94, 95, 132]

列表推导返回布尔列表:

print ([all(y != -1 for y in x) for x in df['mut_position']])
[False, True, False, False]

推荐阅读