Manolo Dominguez Becerra
Manolo Dominguez Becerra

Reputation: 1357

Add the name of a column to the following columna names

I would like to copy the name of the first column and add it to the names of the following columns, I don't know how many columns I will have because I am working with an application that generates data frames with different shapes.

Name      gene_1       gene_2       gene_n
00         01             02           03

Desire output

Name      Name_gene_1       Name_gene_2       Name_gene_n
00          01                  02                03

Upvotes: 0

Views: 38

Answers (1)

picklepick
picklepick

Reputation: 1607

The easiest way would be like this: (can obviously be improved but should be fine for your purpose) This should work for any number of columns, you would just have to update the pre_text variable, or use a predefined list of pre_text values that you could iterate over.

names = list(df.columns) # get column names ['gene_1', 'gene_2' ...]
pre_text = "Name_"
pre_names = []
for name in names:
  pre_names.append(pre_text + name)
df.columns = names # rename columns

Upvotes: 1

Related Questions