pandas rename column if contains string

前端 未结 1 1998
别跟我提以往
别跟我提以往 2021-01-26 17:33

I would like to go through all the columns in a dataframe and rename (or map) columns if they contain certain strings.

For example: rename all columns that contain \'agr

相关标签:
1条回答
  • 2021-01-26 18:22

    You can use str.replace to process the columns first, and then re-assign the new columns back to the DataFrame:

    import pandas as pd
    df = pd.DataFrame({'A_agriculture': [1,2,3],
                       'B_agriculture': [11,22,33],
                       'C': [4,5,6]})
    df.columns = df.columns.str.replace('agriculture', 'agri')
    print df
    

    Output:

       A_agri  B_agri  C
    0       1      11  4
    1       2      22  5
    2       3      33  6
    
    0 讨论(0)
提交回复
热议问题