Remain string on certain position in colum name python

Viewed 39

I'm trying to preprocessing the dataset on kaggle: https://www.kaggle.com/sinaasappel/a-heat-map-divides-patients-into-3-groups. However, in table 1, column names are like:

'C8-A131.01TCGA', 'AO-A12B.01TCGA', 'BH-A18Q.02TCGA', 'C8-A130.02TCGA',
   'C8-A138.03TCGA'...

And I want to merge this table with the row in the other table, which looks like this:

TCGA-A2-A0T2    TCGA-A2-A0CM    TCGA-BH-A18V    TCGA-BH-A18Q    TCGA-BH-A0E0 ...

So I want to clean up the column name in table 1, change it to something like:

'A131', 'A12B', 'A18Q', 'A130', 'A138'

So how can I achieve this? Thanks in advance!

2 Answers

If the pattern is consistent across all the columns, you can use regex to extract values between - and ..

df = pd.DataFrame(columns = ['C8-A131.01TCGA', 'AO-A12B.01TCGA', 'BH-A18Q.02TCGA', 'C8-A130.02TCGA','C8-A138.03TCGA'])

df.columns = df.columns.str.extract('.*-(.*)\..*')[0]

You get

A131    A12B    A18Q    A130    A138

Please split the columns by the alphanumerics \w between - and . and call the index 1 element using .str[1]

df.columns=df.columns.str.split('(?<=\-)(\w+)(?=\.)').str[1]

 

 A131   A12B    A18Q    A130    A138
Related