将带有特定单词的字符串值传输到数据框pandas,python中的其他列

I have the following problem with this example data based in a bigger data with 420 rows. The columns are "m2", "rooms" , and "toilets". I'm using pandas and python.

enter image description here

I would like to transfer the strings that contain the words 'room','rooms','toilet' and 'toilets' from the column 'm2' and the column 'rooms' to their corresponding columns, in this case 'rooms' and 'toilets'. I have problems trying to transfer this values and keeping the row of this information into the data.

评论
  • 巢香莲
    巢香莲 回复

    使用str.contains的条件

    cond1=df.rooms.str.contains('toilet')
    cond2=df.m2.str.contains('room')
    cond3=df.m2.str.contains('toilet')
    

    申请np.where

     df['toilets']=np.where(cond1,df.rooms,df.toilets)
    df['rooms']=np.where(cond2,df.m2,df.rooms)
    df['toilets']=np.where(cond3,df.m2,df.toilets)
    df
    

    平方米的厕所 0 12 1室2洗手间 1 1室1室1洗手间 2 1厕所NaN NaN 3 14 2房间1卫生间 4 3房间3房间NaN