How to apply string methods to multiple columns of a dataframe

前端 未结 3 446
生来不讨喜
生来不讨喜 2021-02-06 02:05

I have a dataframe with multiple string columns. I want to use a string method that is valid for a series on multiple columns of the dataframe. Something like this is what I w

3条回答
  •  广开言路
    2021-02-06 02:21

    Function rstrip working with Series so is possible use apply:

    df = df.apply(lambda x: x.str.rstrip('f'))
    

    Or create Series by stack and last unstack:

    df = df.stack().str.rstrip('f').unstack()
    

    Or use applymap:

    df = df.applymap(lambda x: x.rstrip('f'))
    

    Last if need apply function to some columns:

    #add columns to lists
    cols = ['A']
    df[cols] = df[cols].apply(lambda x: x.str.rstrip('f'))
    df[cols] = df[cols].stack().str.rstrip('f').unstack()
    df[cols] = df[cols].stack().str.rstrip('f').unstack()
    

提交回复
热议问题