python - 如何根据列值在两列中选择数据框中的特定列?
问题描述
我有一个熊猫数据框
_id _score ensembl ensembl.gene notfound
query
Dnmt3a 1788 89.405594 NaN ENSG00000119772 NaN
SUMO1 7341 85.157100 NaN ENSG00000116030 NaN
GADD45a 1647 86.867760 NaN ENSG00000116717 NaN
Rad17 5884 85.377050 [{u'gene': u'ENSG00000155093'}, {u'gene': u'ENSG00000282185'}] NaN NaN
DRS NaN NaN NaN NaN True
根据 'ensembl'、'ensembl.gene' 和 'notfound' 的值,如何找出特定实例的 ensemble id。输出应基于三个条件
如果“ensembl”和“ensembl.gene”的值都是“NaN”,则输出为“未找到”。例如第五排。
如果“ensembl”的值为“NaN”,则只需打印“ensembl.gene”的值,例如第一行、第二行和第三行。
如果“ensembl.gene”的值为“NaN”,则打印“ensembl”值的第一部分,例如在第四行中,“ensembl.gene”的值为“NaN”,因此输出为'ensembl' 值,即 ENSG00000155093。
输出应该是
Ensemble_ID
query
Dnmt3a ENSG00000119772
SUMO1 ENSG00000116030
GADD45a ENSG00000116717
Rad17 ENSG00000155093
DRS Not_found
解决方案
如果我理解正确,这就是您需要的:
import numpy as np
def make_id(row):
if row['ensembl'] is np.nan and row['ensembl.gene'] is np.nan: # 1) If both the value of 'ensembl' and 'ensembl.gene' is 'NaN', then output is "Not found".
return 'Not Found'
elif row['ensembl'] is np.nan: # 2) If the value of 'ensembl' is 'NaN', then just print the value of 'ensembl.gene'
return row['ensembl.gene']
else: # 3) (otherwise) If the value of 'ensembl.gene' is 'NaN', then print first part of the value of 'ensembl'
return row['ensembl'][0]['gene']
df = pd.DataFrame({'ensembl': [np.nan,[{u'gene': u'ENSG00000155093'}],np.nan], 'ensembl.gene':[1,4,5]})
df['id'] = df.apply(lambda row: make_id(row), axis=1)
print(df)
ensembl ensembl.gene id
0 None 1 1
1 [{'gene': 'ENSG00000155093'}] 4 ENSG00000155093
2 None 5 5
这样,您的 df 每一行的 id 都会生成并保存在相应的'id'
列中。
注意:如果缺失值不是由 np.nan 表示,则将 np.nan 替换为算法内部的另一个占位符 'nan'
推荐阅读
- typescript - 在 TypeScript 中声明数组类型的最佳方法?
- javascript - 从查询字符串中删除关联数组
- java - 在骆驼中找到错误的路线
- visual-studio-code - 使用 WSL 在 VS 代码中禁用 Git 扩展
- javascript - 如何为也可以包含视频的 wordpress 帖子制作滑块?
- esbuild - esbuild:如何使用 `loader: { '.css': 'text' }` 结合 `minify: true` 将缩小的 CSS 作为嵌入文本?
- c# - 在 EF Core 中为一对一关系定义具有特定列名的实体
- jquery - jQuery日期选择器没有输出
- python - 使用 Python 在 Bot Framework 中使用中间件获取 Bot 响应
- python - MlFlow:找不到使用 api 的运行