pandas 通过apply()创建两个新的列,其中一个旧列

djmepvbi  于 2023-03-21  发布在  其他
关注(0)|答案(1)|浏览(124)

min示例

exonbed=pd.DataFrame(['NM_1234','NM_123456','NM_1234567'],columns =['trid'])
gene_trid_reverse={'NM_1234':'gene1','NM_123456':'gene2'}

我尽力了

exonbed[['gene','isMANE']]=exonbed['trid'].apply(lambda x : (gene_trid_reverse[x],'MANE' if x in  gene_trid_reverse else x,'NO MANE') ,result_type='expand' )

埃罗

TypeError: <lambda>() got an unexpected keyword argument 'result_type'

我也尝试过,

exonbed['gene_isMANE']=exonbed['trid'].apply(lambda x : (gene_trid_reverse[x],'MANE') if x in  gene_trid_reverse else (x,'NO MANE'))

exonbed['gene']=exonbed['gene_isMANE'].str.split(',')[0]
exonbed['isMANE']=exonbed['gene_isMANE'].str.split(',')[1]

但是cols基因和isMANE基因中均为NA

trid            gene_isMANE  gene  isMANE
0     NM_1234          (gene1, MANE)   NaN     NaN
1   NM_123456          (gene2, MANE)   NaN     NaN
2  NM_1234567  (NM_1234567, NO MANE)   NaN     NaN

也许将其转换为字符串而不是集合会有所帮助?但我想知道最直接的应用方法。

iklwldmw

iklwldmw1#

用途:

L = exonbed['trid'].apply(lambda x : (gene_trid_reverse[x],'MANE')
                                      if x in gene_trid_reverse 
                                      else (x,'NO MANE'))
exonbed[['gene','isMANE']] = pd.DataFrame(L, index=exonbed.index)

或者:

L = [(gene_trid_reverse[x],'MANE') 
     if x in gene_trid_reverse 
     else (x,'NO MANE') for x in exonbed['trid']]
exonbed[['gene','isMANE']] = pd.DataFrame(L, index=exonbed.index)

相关问题