首页 > 解决方案 > 如何根据列值在两列中选择数据框中的特定列?

问题描述

我有一个熊猫数据框

        _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。输出应基于三个条件

  1. 如果“ensembl”和“ensembl.gene”的值都是“NaN”,则输出为“未找到”。例如第五排。

  2. 如果“ensembl”的值为“NaN”,则只需打印“ensembl.gene”的值,例如第一行、第二行和第三行。

  3. 如果“ensembl.gene”的值为“NaN”,则打印“ensembl”值的第一部分,例如在第四行中,“ensembl.gene”的值为“NaN”,因此输出为'ensembl' 值,即 ENSG00000155093。

输出应该是

    Ensemble_ID
query                   
Dnmt3a  ENSG00000119772
SUMO1   ENSG00000116030
GADD45a ENSG00000116717
Rad17   ENSG00000155093
DRS     Not_found

标签: pythonpandasdataframe

解决方案


如果我理解正确,这就是您需要的:

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'


推荐阅读