从熊猫数据框中的列中排序特定值

时间:2018-06-30 15:16:42

标签: pandas

我有一个数据框,例如:

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)或一些数字的列表。 例如它可以是001中的-1。像002中那样的少数列表或一个数字-例如4。 我需要计算没有-1的主题的数量。

我试图通过与-1进行比较,并收集r不同但似乎起作用的值...

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

我对两者的理解都为真(忽略ref_aa_len,应该稍后再发布)-

0    True
1    True

1 个答案:

答案 0 :(得分:1)

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

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]

列表理解返回boolena列表:

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