[Python] Search pattern not unique? - Regular expression

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I want to write a function to clean the index column of the dataframe.


    1. Delete the whole row that has high-level IDs. For example, delete

      East Kootenay (5901) 01010


    2. Tailor the index into 7-digit number for low-level IDs. For example, turn

      East Kootenay A (5901017) RDA 02020 into 5901017


    3. If it has two parenthesis keep only the 7-digit number in the second parenthesis. For example,

      Sechelt (Part) (5929803) IGD 02020 to 5929803

      Capital H (Part 1) (5917054) RDA 01020 to 5917054

      Capital H (Part 2) (5917056) RDA 02030 to 5917056

      T'Sou-ke 1 (Sooke 1) (5917817) IRI 01010 to 5917817

      T'Sou-ke 2 (Sooke 2) (5917818) IRI 00000 to 5917818

    An example of code only works for one bracket is

    def extract_id(s):
    m = re.search('\((.*)\)', s)
    if m:
    i = int(m.group(0)[1:-1])
    return i

    if __name__ == '__main__':
    # Read data
    census_subdivision_profile = pd.read_excel('../data/census_subdivision_profile.xlsx', sheetname='Data',
    index_col='Geography', encoding='utf-8').T
    print(census_subdivision_profile.head())
    print(census_subdivision_profile.shape)

    census_subdivision_profile.index = census_subdivision_profile.index.map(extract_id)
    print(census_subdivision_profile.index)


    To see the full code, see another question I posted earlier

    Merge dataframes that have indices that one contains another (but not the same)

    Continue reading...

Compartilhe esta Página