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) 或少数数字的列表。例如,它可以是 -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
解决方案
我认为需要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]
推荐阅读
- c# - Dotnet - 如何使用 CLI 更改目标框架?
- javascript - JavaScript:如何拆分具有多个分隔符的字符串并排除分隔符?
- c# - 已发布的 .Net Core C# 控制台应用程序未找到 COM 依赖项(“未找到应用程序依赖项清单中指定的程序集”)?
- android - Xamarin android Glide webp 动画
- laravel - 我如何将动态值从表单(发布方法)发送回控制器
- workflow - 通过自定义工作流触发时未执行推出
- python - 在 conda 环境中“找不到 PythonLibs”
- vue.js - ThreeJS 组件在 VueJS 2 但不是 3
- firebase - 颤振状态生成器问题列表
- api-key - 为什么 google-slides rest API 会忽略我的 api-key?