Search code examples
pythonpandasmultiple-columns

Same column name in Pandas need to be removed


I have a dataframe with same columnNames.I want to remove one particular repeated column.

In the below data frame, I want to remove all columns with Name Numbers and keep Alphabets. How could I achieve this

data = pd.DataFrame({'Alphabets': ['A', 'B', 'C'],
                     'Numbers': ['1', '2', '3'],
                      'Alphabets': ['D', 'E', 'F'],
                     'Numbers': ['10', '11', '12'],
                     'Alphabets': ['G', 'H', 'I'],
                     'Numbers': ['13', '14', '15']})

Solution

  • Try removing any columns that match with a specific term, like this:

    df= df.loc[:, ~df.columns.str.match('Numbers')]
    

    It will remove any columns that contains Numbers as names