首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据python中的其他两列为列赋值

根据python中的其他两列为列赋值
EN

Stack Overflow用户
提问于 2017-10-18 11:12:40
回答 1查看 17关注 0票数 1

我有两个专栏转发,并提到如下

代码语言:javascript
复制
retweet              mention

RT @CritCareMed:    
                     @CellCellPress
RT @CritCareMed:     @mother
RT @gvwilson:           
RT @sciencemagazine:        
RT @MHendr1cks:      @nucAmbiguous
                     @air

我想要一个新的列,基于它是一个转发,还是在新的行中提到和赋值M,如果它是一个提到,其他赋值R。如果提到和转发都存在,那么行应该有值M,因此最终结果应该是

代码语言:javascript
复制
 retweet                mention             Type

RT @CritCareMed:                              R
                        @CellCellPress        M
RT @CritCareMed:        @mother               R,M
RT @gvwilson:                                 R
RT @sciencemagazine:                          R
RT @MHendr1cks:         @nucAmbiguous         R,M
                        @air                  M

我现在正在做的事情就像

代码语言:javascript
复制
df = df.assign(Type=np.where(df.retweet.isnull(), 'M','R'))

但它给了我结果

代码语言:javascript
复制
             retweet             mention        Type  
      RT @CritCareMed:             NaN           R  
                 NaN       @CellCellPress        M  
       RT @CritCareMed:         @mother          M  
          RT @gvwilson:             NaN          R  
   RT @sciencemagazine:             NaN          R  
        RT @MHendr1cks:   @nucAmbiguous          M  
                  NaN           @air             M 

第3行和第6行应该有R,M类型,但它只是给了我M(正如代码中所期望的)。如何修改代码以获得上述结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-18 11:24:49

添加检查另一列的另一个条件:

代码语言:javascript
复制
df = df.assign(Type=np.where(df.retweet.isnull(), 'M',
                    np.where(df.mention.isnull(), 'R','R, M')))
print (df)
                retweet         mention  Type
0      RT @CritCareMed:             NaN     R
1                   NaN  @CellCellPress     M
2      RT @CritCareMed:         @mother  R, M
3         RT @gvwilson:             NaN     R
4  RT @sciencemagazine:             NaN     R
5       RT @MHendr1cks:   @nucAmbiguous  R, M
6                   NaN            @air     M
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46808866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档