Pandas how can 'replace' work after 'loc'?

前端 未结 3 747
终归单人心
终归单人心 2020-12-03 19:35

I have tried many times, but seems the \'replace\' can NOT work well after use \'loc\'. For example I want to replace the \'conlumn_b\' with an regex for the row that the \'

3条回答
  •  Happy的楠姐
    2020-12-03 20:06

    I'm going to borrow from a recent answer of mine. This technique is a general purpose strategy for updating a dataframe in place:

    df.update(
        df.loc[df['conlumn_a'] == 'apple', 'conlumn_b']
          .replace(r'^11$', 'XXX', regex=True)
    )
    
    df
    
      conlumn_a conlumn_b
    0     apple       123
    1    banana        11
    2     apple       XXX
    3    orange        33
    

    Note that all I did was remove the inplace=True and instead wrapped it in the pd.DataFrame.update method.

提交回复
热议问题